简体   繁体   中英

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?

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

您正在设置默认值(此外,使用一个没有任何意义的块)而不设置任何键值对。

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