Ruby:Hash(雜湊)學習,你可以理解為字典

weixin_34120274發表於2018-12-23

原文連結

以下程式碼在Ruby 2.5.1中編譯通過

定義

myHash = Hash.new
myHash1 = Hash["key1" => 100, "key2" => 200]
myHash2 = Hash.new("defualtValue") # 建立帶有預設值的Hash,當訪問不存在的任意key,返回該值
myHash3 = Hash.new "defualtValue" # 建立帶有預設值的Hash,當訪問不存在的任意key,返回該值

puts myHash1["key1"] # defualtValue

賦值

myHash = {"key1" => "value1", "key2" => "value2"}

修改/新增元素

myHash["key3"] = 300 # key不存在新增則新增
myHash["key3"] = 200 # key存在則更新/修改value

puts myHash["key3"] # 200

取值

value = myHash["key2"]

元素個數

count = myHash.count

key/value

keys = myHash.keys    # 獲取所有key
values = myHash.values # 獲取所有values

Hash遍歷

方法1

myHash.each { |key, value|

  puts key
  puts value
}

方法2

for key in myHash.keys do

  value = myHash[key]
  puts value
end

方法3

for value in myHash.values do

  puts value
end

方法4

myHash.values.each { |value|

  puts value
}

方法5

myHash.keys.each { |key|

  puts key
}

相關文章