ruby - Hash of hashes from an array -
from array:
this = [1, 2, 3, 4, 5]
i trying create hash of hashes:
{{num: 1}, {num: 2}, {num: 3}, {num: 4}, {num: 5}}
but i'm getting empty hash:
hash.new(this.each |num| hash.new(num: num) end) # => {}
what doing wrong?
first, desired result in question doesn't make sense since you're using hash {}
syntax, there no keys. seems though want result array of hashes.
second, you're confusing each
map
. each
iterates through array, passing each item block. return value of arr.each
arr
. map
, on other hand, returns new array based on return value of block:
[1, 2, 3, 4, 5].map { |item| { num: item } }
Comments
Post a Comment