以下代码在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 # 获取所有key

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
}

本文由 Harvey 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论