开发者

iterating hash collection

{"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"
}


myHash.each do |key, value|
  // key holds the key, value holds the value
end

In case want to transform the arrays inside your array to a map do this:

myNewHash = {}
myArrayOfArrays = myHash["Journal"]
myArrayOfArrays.each do | item |
  myNewHash[item[0]] = item[1]
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜