0

通过哈希进行迭代时,无法更改键。假设您要为每个键添加“_new”:

hash = { 'a' => 1, 'b' => 2 }

new_pairs = Hash.new

hash.each do | k,v |
  new_pairs[ k + '_new' ] = v

  hash.delete k
end

hash.merge! new_pairs

有没有一种更清洁、更惯用的类似红宝石的方式来做到这一点?

4

5 回答 5

3

您不需要就地突变 ( merge!)。我会做这样的事情:

hash = { 'a' => 1, 'b' => 2 }

hash2 = Hash[hash.map{|k, v| [k + '_new', v] }]

hash2 # => {"a_new"=>1, "b_new"=>2}
于 2013-10-28T19:36:38.457 回答
2

您不能在修改哈希时直接迭代它,但您可以迭代keys.

hash.keys.each{|k| hash["#{k}_new"] = hash.delete(k)}
于 2013-10-28T19:44:23.097 回答
2

任你选!

    hash = hash.keys.reduce({}) {|h,k| h[k + '_new'] = hash[k]; h}   
于 2013-10-28T21:25:17.163 回答
1
hash.map { |k, v| {"#{k}_new" => v} }.reduce(:merge)
于 2013-10-28T20:43:41.523 回答
0

我会做如下:

hash = { 'a' => 1, 'b' => 2 }
nw_hash = Hash.new { |hsh, key| hsh[key+'_new'] = hash[key] }
hash.keys.each{|e| nw_hash[e] }
nw_hash
# => {"a_new"=>1, "b_new"=>2}
于 2013-10-28T19:41:19.600 回答