mila002 mila002 - 1 year ago 54
Ruby Question

Creating hash from array adding new keys

I have an array looking like this:

data =[[01, 777], [02, 888]]

Now I want to create a hash from it like below:

n_clip = [{"name"=>"01", "rep"=>"777"},{"name"=>"02", rep=>"888"}]

I tried to do this in that way:

n_clip = []
data.each do |a|
n_clip << Array[Hash[ {|| ["name", a.first]}], Hash[ {|| ["rep", a.last]}]]

but it doesn't work because I get:

n_clip = [[{"name"=>"01"},{"rep"="777"}], [{"name"=>"01"},{"rep"="777"}]]

and definitively it isn't what I expected.

Answer Source { |arr| { 'name' => arr[0], 'rep' => arr[1] } }

i would rather use symbols as hash keys { |arr| { name: arr[0], rep: arr[1] } }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download