[[4, -785.0], [13, -21.9165000915527], [14, -213.008995056152], [15, -50.074499130249]]} How can you repea...">

Iterating Hash Collection

{"Journal"=>[[4, -785.0], [13, -21.9165000915527], [14, -213.008995056152], [15, -50.074499130249]]} 

How can you repeat this hash in Ruby, and how would you highlight keys and values?

+7
ruby mapping hash
source share
2 answers

Ruby has a unified iteration interface. All Ruby collections have each method, which allows you to iterate over each element of the collection. Note, however, that explicit iteration is the smell of code. Basically, you should use higher level iterators like map , reduce , select , find , reject , etc.

In this particular case, when the collection is Hash , each element that is passed to your block is a two-element array consisting of a key and a value:

 print hsh.reduce('') {|s, el| s << "The key is #{el.first} and the value is #{el.last}.\n" } 

Thanks to the Ruby destructuring bind, you can simply bind two elements of an array to two variables in your block, and you do not have to constantly allocate an array:

 print hsh.reduce('') {|s, (k, v)| s << "The key is #{k} and the value is #{v}.\n" } 
+21
source share
 myHash.each do |key, value| // key holds the key, value holds the value end 

If you want to convert arrays inside your array to a map, do the following:

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

All Articles