mila002 mila002 - 2 months ago 8
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[a.map {|| ["name", a.first]}], Hash[a.map {|| ["rep", a.last]}]]
end


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
data.map { |arr| { 'name' => arr[0], 'rep' => arr[1] } }

i would rather use symbols as hash keys

data.map { |arr| { name: arr[0], rep: arr[1] } }
Comments