hash = {:one => 1, :two => 2, :three => 3}
new_hash = hash.each { |k, v| v.to_int * 5 }
new_hash
我想要这个输出:
=> {"one"=>5, "two"=>10, "three"=>15}
但我明白了:
=> {"one"=>1, "two"=>2, "three"=>3}
为什么?
答案 0 :(得分:2)
each
返回原始哈希值。你必须建立一个新的:
new_hash = hash.map { |k, v| [k, v * 5] }.to_h
#=> {:one=>5, :two=>10, :three=>15}
或者对于Ruby< 2.1
new_hash = Hash[hash.map { |k, v| [k, v * 5] }]
#=> {:one=>5, :two=>10, :three=>15}
答案 1 :(得分:0)
正如您在documentation中看到的那样,Hash#each
会返回原始哈希值,然后您将其分配给new_hash
。
请改为:
hash = {:one => 1, :two => 2, :three => 3}
new_hash = Hash[hash.map { |k, v| [k, v * 5] }]
new_hash # => {:one=>5, :two=>10, :three=>15}
答案 2 :(得分:0)
您可以执行以下操作:
hash = {:one => 1, :two => 2, :three => 3}
new_hash = hash.reduce({}) { |h, (k, v) | h[ k ] = v.to_i * 5 ; h }
# => {:one=>5, :two=>10, :three=>15}
答案 3 :(得分:0)
当给出一个块时,each
Hash
方法返回原始哈希而不进行修改。请参阅ruby doc。