迭代哈希集合 [英] iterating hash collection
问题描述
{Journal=> [[4,-785.0],
[13,-21.9165000915527],
[14,-213.008995056152],
[15,-50.074499130249]]}
如何在Ruby中迭代这个散列,你将如何分离出钥匙&值?
Ruby有一个统一的迭代界面。 Ruby中的所有集合都有一个名为的方法,每个
,它允许您遍历集合中的每个元素。但是请注意,显式迭代是一种代码异味。你应该主要使用更高级的迭代器,比如 map
, reduce
, select
, find
,拒绝
等等。
在这个集合是 Hash
的特定情况下,每个被放到块中的元素是一个由元素和值组成的双元素数组:
print hsh.reduce(''){| s,el |
s<< 关键是#{el.first},值是#{el.last}。\ n
}
感谢Ruby的解构绑定,您可以简单地将数组的两个元素绑定到块中的两个变量,而不需要不断地将数组分开:
print hsh.reduce(''){| s,(k,v)|
s<< 关键是#{k},值是#{v}。\ n
}
{"Journal"=>[[4, -785.0],
[13, -21.9165000915527],
[14, -213.008995056152],
[15, -50.074499130249]]}
How can you to iterate this hash in Ruby, and how would you to separate out keys & values?
Ruby has a uniform iteration interface. All collections in Ruby have a method called each
, which allows you to iterate over each element of the collection. Note, however, that explicit iteration is a code smell. You should mostly use higher-level iterators like map
, reduce
, select
, find
, reject
and such.
In this particular case where the collection is a Hash
, each element that is being yielded to your block, is a two-element array consisting of the key and the value:
print hsh.reduce('') {|s, el|
s << "The key is #{el.first} and the value is #{el.last}.\n"
}
Thanks to Ruby's destructuring bind, you can simply bind the two elements of the array to two variables in your block and you won't have the need to constantly take the array apart:
print hsh.reduce('') {|s, (k, v)|
s << "The key is #{k} and the value is #{v}.\n"
}
这篇关于迭代哈希集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!