mila002
mila002

Reputation: 385

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.

Upvotes: 3

Views: 47

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

If you wish to create an array of two hashes, each having the same two keys, the other answers are fine. The following handles the case where there are an arbitrary number of keys and data may contain an arbitrary number of elements.

def hashify(keys, arr_of_vals)
  [keys].product(arr_of_vals).map { |ak,av| Hash[ak.zip(av)] }
end

keys = %w| name rep |
  #=> ["name", "rep"] 
arr_of_vals = [["01", "777"], ["02", "888"]]
hashify(keys, arr_of_vals)
  #=> [{"name"=>"01", "rep"=>"777"}, {"name"=>"02", "rep"=>"888"}]

In your problem arr_of_vals must first be derived from [[1, 777], [02, 888]], but that is a secondary (rather mundane) problem that I will not address.

Another example:

keys = %w| name rep group |
  #=> ["name", "rep", "group"] 
arr_of_vals = [[1, 777, 51], [2, 888, 52], [1, 2, 53], [3, 4, 54]]
hashify(keys, arr_of_vals)
  #=> [{"name"=>1, "rep"=>777, "group"=>51}, {"name"=>2, "rep"=>888, "group"=>52},
  #    {"name"=>1, "rep"=>2, "group"=>53}, {"name"=>3, "rep"=>4, "group"=>54}] 

Upvotes: 1

Ginty
Ginty

Reputation: 3501

data.map { |name, rep| { 'name' => name.to_s, 'rep' => rep.to_s } }

Upvotes: 0

jan.zikan
jan.zikan

Reputation: 1316

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] } }

Upvotes: 1

Related Questions