maza
maza

Reputation: 13

How to build a new Ruby array from a Hash keys

I want to build a new array starting from a hash with the following format:

HashConst = {[120,240] => 60, [240,480]=> 30} #Constant

I need to build a new array and assign as value to a new constant with the following format:

[ [[120,240] ,1], [[240,480], 1] ]

I tried :

NewArrayConst = HashConst.keys.each{ |res| [res, 1]}

but I get instead

[ [120,240], [240,480] ]

Only solution I found is the following:

  tempVar = []
  HashConst.keys.each_with_index{ |res,idx| tempVar [idx] = [res, 1]}
  NewArrayConst = tempVar 

Anyone knows a better solution to this and can explain why I cannot get the output I expect from NewArrayConst = HashConst.keys.each{ |res| [res, 1]}. I'm using 2.2.2-p95

Edit:

As many pointed out Hash var name is wrong and misleading, I have updated that to avoid confusion

Upvotes: 0

Views: 74

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110755

h = {[120,240] => 60, [240,480]=> 30}
val = 1

h.keys.product([val])
  #=> [[[120, 240], 1], [[240, 480], 1]] 

Upvotes: 3

Wand Maker
Wand Maker

Reputation: 18772

You need to use map instead of each.

Array#each method does not return the result of the code executed in the block, but instead just returns the array on which each was called, which in your case is the value of hash.keys.

Array#map collects the values returned by block into an array.

hash = {[120,240] => 60, [240,480]=> 30}
p array = hash.keys.map{ |res| [res, 1]}
#=> [[[120, 240], 1], [[240, 480], 1]]

NOTE: Do not name your variable Hash as it is already a well-known class in Ruby. Use lower case hash if need be. Also, avoid camel case for variable names such as NewArrayConst, as Ruby recommends use of snake_case for naming variables - you can refer Ruby Style Guide for more details.

Upvotes: 5

linuxdan
linuxdan

Reputation: 4864

Have you tried Hash.to_a? Sometimes things are easier than you think.

Upvotes: -2

Related Questions