3

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.

3 Answers 3

1
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] } }
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

1 Comment

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.