Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 289
Fenec Avatar asked Jul 17 '13 13:07

Fenec


2 Answers

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"}
like image 64
Arup Rakshit Avatar answered Oct 12 '22 22:10

Arup Rakshit


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"} 
like image 21
Santhosh Avatar answered Oct 12 '22 22:10

Santhosh