從一個數組:哈希散列從一個數組
this = [1, 2, 3, 4, 5]
我想創建哈希散列:
{{num: 1}, {num: 2}, {num: 3}, {num: 4}, {num: 5}}
但我發現了一個空的哈希:
Hash.new(this.each do |num| Hash.new(num: num) end)
# => {}
我在做什麼錯了?
從一個數組:哈希散列從一個數組
this = [1, 2, 3, 4, 5]
我想創建哈希散列:
{{num: 1}, {num: 2}, {num: 3}, {num: 4}, {num: 5}}
但我發現了一個空的哈希:
Hash.new(this.each do |num| Hash.new(num: num) end)
# => {}
我在做什麼錯了?
首先,由於您使用的是Hash {}
語法,所以在您的問題中所需的結果沒有意義,但沒有鍵。看起來好像你希望你的結果是散列數組。
其次,你很困惑each
與map
。 each
只是遍歷數組,將每個項目傳遞給塊。 arr.each
的返回值僅爲arr
。 map
,在另一方面,返回基於塊的返回值的新的數組:
[1, 2, 3, 4, 5].map { |item| { num: item } }
,雖然返回散列的陣列。 – teddybear
{{num:1},{num:2},{num:3},{num:4},{num:5}}不是有效的散列,並且散列不能具有多於一旦。 –
請提供您想要的輸出。您發佈爲期望輸出的數據結構不是合法的Ruby數據結構。這甚至不是合法的Ruby語法。 –