如何在哈希中为每个键添加前缀?

时间:2013-07-17 13:19:17

标签: ruby

我的哈希中有以下键:

address, postcode

我想为每个人添加“shipping_”前缀,以便它们成为:

shipping_address, shipping_postcode

代替。我怎么能这样做?

3 个答案:

答案 0 :(得分:9)

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

<强>更新

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

答案 1 :(得分:4)

如果你想破坏性地做这件事,这是一个很短的方法:

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

答案 2 :(得分:3)

在Ruby> = 2.5中,您可以做到

hsh.transform_keys! {|k| 'shipping_' + k }