Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a Hash of Arrays into an Array of Hashes in Ruby

Tags:

arrays

ruby

hash

We have the following datastructures:

{:a => ["val1", "val2"], :b => ["valb1", "valb2"], ...}

And I want to turn that into

[{:a => "val1", :b => "valb1"}, {:a => "val2", :b => "valb2"}, ...]

And then back into the first form. Anybody with a nice looking implementation?

like image 211
Julien Genestoux Avatar asked Oct 29 '09 00:10

Julien Genestoux


People also ask

How do you make an Array of hashes in Ruby?

Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.

What is the difference between Array and Hash in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.

How do you make Hash Hash in Ruby?

Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.


1 Answers

Using a functional approach (see Enumerable):

hs = h.values.transpose.map { |vs| h.keys.zip(vs).to_h }
#=> [{:a=>"val1", :b=>"valb1"}, {:a=>"val2", :b=>"valb2"}]

And back:

h_again = hs.first.keys.zip(hs.map(&:values).transpose).to_h
#=> {:a=>["val1", "val2"], :b=>["valb1", "valb2"]}
like image 198
tokland Avatar answered Oct 27 '22 01:10

tokland