Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating hash from array adding new keys

Tags:

arrays

ruby

hash

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.

like image 908
mila002 Avatar asked Dec 31 '25 15:12

mila002


2 Answers

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] } }
like image 87
jan.zikan Avatar answered Jan 03 '26 14:01

jan.zikan


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}] 
like image 42
Cary Swoveland Avatar answered Jan 03 '26 12:01

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!