I have the following keys in my hash:
address, postcode
I want to add the "shipping_" prefix to each of them so they would become:
shipping_address, shipping_postcode
instead. How can I do this?
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With