Ruby: Create array of hashes from multiple arrays
Mar
28
We have two or more arrays, and we would like to create hashes from these. For example: one of the arrays contains the names of our users, the another one contains the birth years, and the third contains the room numbers. We would like to create a hash for every user.
irb(main):001:0> name=['John','Jack','Jake']
=> ["John", "Jack", "Jake"]
irb(main):002:0> year=[1958, 1976, 1984 ]
=> [1958, 1976, 1984]
irb(main):003:0> room=[501,502,503]
=> [501, 502, 503]
irb(main):004:0> name.zip(year,room).map{|x| Hash[['name','year','room'].zip(x)]}
=> [{"name"=>"John", "year"=>1958, "room"=>501},
{"name"=>"Jack", "year"=>1976, "room"=>502},
{"name"=>"Jake", "year"=>1984, "room"=>503}]