Ruby to hash mapping array

I have a 2D array with each line like:

['John', 'M', '34']

I want to map to a Hash array with each hash, for example:

{:Name=>"John", :Gender=>"M", :Age=>"34"}

Is there an elegant way to do this?

+3


source to share


5 answers


array_of_rows.map { |n,g,a| { Name: n, Gender: g, Age: a } }

      

or

array_of_rows.map { |row| %i{Name Gender Age}.zip(row).to_h }

      

They give the same result, so choose one that you find clearer. For example, given this input:



array_of_rows = [
  ['John', 'M', '34'],
  ['Mark', 'M', '49']
]

      

any expression will give this output:

[{:Name=>"John", :Gender=>"M", :Age=>"34"}, 
 {:Name=>"Mark", :Gender=>"M", :Age=>"49"}]

      

+6


source


You can try using zip

and then to_h

(which means hash)

For example:

[:Name, :Gender, :Age].zip(['John', 'M', '34']).to_h
=> {:Name=>"John", :Gender=>"M", :Age=>"34"}

      



More about zip

here

And read about to_h

here

+4


source


people = [['John', 'M', '34']]
keys = %i{Name Gender Age}

hashes = people.map { |person| keys.zip(person).to_h }
# => [{:Name=>"John", :Gender=>"M", :Age=>"34"}]

      

Basically the way I turn on concatenating two arrays into a hash (one with keys, one with values) is to use Array # zip . It can turn [1,2,3]

and [4,5,6]

in[[1,4], [2,5], [3,6]]

This structure can easily be turned into a hash via to_h

+3


source


array_of_rows = [
  ['John', 'M', '34'],
  ['Mark', 'M', '49']
]

keys = ['Name', 'Gender', 'Age']

[keys].product(array_of_rows).map { |k,v| k.zip(v).to_h }
  #=> [{"Name"=>"John", "Gender"=>"M", "Age"=>"34"},
  #    {"Name"=>"Mark", "Gender"=>"M", "Age"=>"49"}]

      

or

keys_cycle = keys.cycle
array_of_rows.map do |values|
  values.each_with_object({}) { |value, h| h[keys_cycle.next]=value }
do

      

+1


source


Here's another way to do it

array_of_rows = [
  ['John', 'M', '34'],
  ['Mark', 'M', '49']
]

keys = [:Name, :Gender, :Age]

array_of_rows.collect { |a| Hash[ [keys, a].transpose] }
#=>[{:Name=>"John", :Gender=>"M", :Age=>"34"}, {:Name=>"Mark", :Gender=>"M", :Age=>"49"}]

      

0


source







All Articles