简体   繁体   中英

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

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM