Pergunta

When iterating though a hash, keys cannot be changed. Suppose you want to add '_new' to each key:

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

Is there a cleaner, more idiomatic ruby-like way of doing this?

Foi útil?

Solução

You don't need in-place mutations (merge!). I'd do something like this:

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

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

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

Outras dicas

You cannot directly iterate though a hash while modifying it, but you can iterate over keys.

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

Take your pick!

    hash = hash.keys.reduce({}) {|h,k| h[k + '_new'] = hash[k]; h}   
hash.map { |k, v| {"#{k}_new" => v} }.reduce(:merge)

I would do as below :

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}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top