在Ruby中更新哈希键的惯用方法是什么?

时间:2013-10-28 19:33:53

标签: ruby hash iterator refactoring enumerable

迭代哈希时,无法更改密钥。假设您要为每个键添加“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

这样做是否有更干净,更像惯用的类似红宝石的方式?

5 个答案:

答案 0 :(得分:3)

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

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

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

hash2 # => {"a_new"=>1, "b_new"=>2}

答案 1 :(得分:2)

修改时不能直接遍历哈希,但可以迭代keys

hash.keys.each{|k| hash["#{k}_new"] = hash.delete(k)}

答案 2 :(得分:2)

接受你的选择!

    hash = hash.keys.reduce({}) {|h,k| h[k + '_new'] = hash[k]; h}   

答案 3 :(得分:1)

hash.map { |k, v| {"#{k}_new" => v} }.reduce(:merge)

答案 4 :(得分: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}