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?
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"}]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With