teddybear
teddybear

Reputation: 570

Hash of hashes from an array

From an array:

this = [1, 2, 3, 4, 5]

I am trying to create a hash of hashes:

{{num: 1}, {num: 2}, {num: 3}, {num: 4}, {num: 5}}

But I'm getting an empty hash:

Hash.new(this.each do |num| Hash.new(num: num) end)
# => {}

What am I doing wrong?

Upvotes: 1

Views: 64

Answers (2)

Anthony E
Anthony E

Reputation: 11235

First, your desired result in your question doesn't make sense since you're using the Hash {} syntax, but there are no keys. It seems as though you want your result to be an array of hashes.

Second, you're confusing each with map. each simply iterates through an array, passing each item to the block. The return value of arr.each is just arr. map, on the other hand, returns a new array based on the return value of the block:

[1, 2, 3, 4, 5].map { |item| { num: item } }

Upvotes: 5

sawa
sawa

Reputation: 168091

You are setting the default value (furthermore with a block that does not do anything meaningful) without setting any key-value pairs.

Upvotes: 1

Related Questions