iterating hash collection

2019-04-26 01:58发布

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

2条回答
劫难
2楼-- · 2019-04-26 02:27

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"
}
查看更多
【Aperson】
3楼-- · 2019-04-26 02:36
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
查看更多
登录 后发表回答