Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby mapping array into hash

Tags:

arrays

ruby

hash

I have a 2D array with each row like:

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

I want to map into an array of Hash with each hash like:

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

Is there an elegant way of doing that?

like image 203
some user Avatar asked Dec 04 '22 22:12

some user


2 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 produce the same result, so pick the one you find clearer. For example, given this input:

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

either expression will yield this output:

[{:Name=>"John", :Gender=>"M", :Age=>"34"}, 
 {:Name=>"Mark", :Gender=>"M", :Age=>"49"}]
like image 137
Mark Reed Avatar answered Jan 15 '23 01:01

Mark Reed


You could try using zip and then to_h (which stands for to hash)

For example:

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

Read more about zip here

And read about to_h here

like image 21
yez Avatar answered Jan 15 '23 01:01

yez