{"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?
{"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 likemap
,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: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:
In case want to transform the arrays inside your array to a map do this: