How do I add a prefix to each key in a hash?

hsh1 = {'address' => "foo", 'postcode' => "bar"}
hsh2 = Hash[hsh1.map{|k,v| [k.dup.prepend("shipping_"),v]}]
p hsh2
# >> {"shipping_address"=>"foo", "shipping_postcode"=>"bar"}

update

hsh1 = {'address' => "foo", 'postcode' => "bar"}
hsh2 = Hash[hsh1.map{|k,v| ["shipping_#{k}",v]}]
p hsh2
# >> {"shipping_address"=>"foo", "shipping_postcode"=>"bar"}

In Ruby >= 2.5, you can do

hsh.transform_keys! {|k| 'shipping_' + k }
# => {"shipping_address"=>"foo", "shipping_postcode"=>"bar"} 

And if you want to be fancy

hsh.transform_keys! &'shipping_'.method(:+)
# => {"shipping_address"=>"foo", "shipping_postcode"=>"bar"} 

If you want to do it destructively, this is a short way:

hash.keys.each{|k| hash.store("shipping_#{k}", hash.delete(k))}

Tags:

Ruby