{"Journal"=>[[4, -785.0],
[13, -21.9165000915527],
[14, -213.008995056152],
[15, -50.074499130249]]}
如何在Ruby中迭代此哈希表,并如何将键和值分离?
each
的方法,允许您迭代集合中的每个元素。但请注意,显式迭代是一种代码异味。您应该主要使用高级迭代器,如map
、reduce
、select
、find
、reject
等。Hash
,那么传递给您的块的每个元素都是一个由键和值组成的两个元素的数组:print hsh.reduce('') {|s, el|
s << "The key is #{el.first} and the value is #{el.last}.\n"
}
得益于 Ruby 的解构绑定,您可以在块中将数组的两个元素绑定到两个变量上,无需不断地拆开数组:
print hsh.reduce('') {|s, (k, v)|
s << "The key is #{k} and the value is #{v}.\n"
}
myHash.each do |key, value|
// key holds the key, value holds the value
end
如果你想将数组中的数组转换为一个映射,请按照以下步骤进行:
myNewHash = {}
myArrayOfArrays = myHash["Journal"]
myArrayOfArrays.each do | item |
myNewHash[item[0]] = item[1]
end