迭代哈希
Hash
包含 Enumerable
模块,它提供了几种迭代方法,例如:Enumerable#each
,Enumerable#each_pair
,Enumerable#each_key
和 Enumerable#each_value
。
.each
和 .each_pair
遍历每个键值对:
h = { "first_name" => "John", "last_name" => "Doe" }
h.each do |key, value|
puts "#{key} = #{value}"
end
# => first_name = John
# last_name = Doe
.each_key
仅迭代密钥:
h = { "first_name" => "John", "last_name" => "Doe" }
h.each_key do |key|
puts key
end
# => first_name
# last_name
.each_value
仅迭代值:
h = { "first_name" => "John", "last_name" => "Doe" }
h.each_value do |value|
puts value
end
# => John
# Doe
.each_with_index
迭代元素并提供迭代的索引:
h = { "first_name" => "John", "last_name" => "Doe" }
h.each_with_index do |(key, value), index|
puts "index: #{index} | key: #{key} | value: #{value}"
end
# => index: 0 | key: first_name | value: John
# index: 1 | key: last_name | value: Doe