在 Ruby 中更改散列中的每个值 [英] Changing every value in a hash in Ruby

查看:25
本文介绍了在 Ruby 中更改散列中的每个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改散列中的每个值,以便在值前后添加'%'

I want to change every value in a hash so as to add '%' before and after the value so

{ :a=>'a' , :b=>'b' }

必须改为

{ :a=>'%a%' , :b=>'%b%' }

最好的方法是什么?

推荐答案

如果您希望实际的字符串本身就地发生变化(可能并且希望影响对相同字符串对象的其他引用):

If you want the actual strings themselves to mutate in place (possibly and desirably affecting other references to the same string objects):

# Two ways to achieve the same result (any Ruby version)
my_hash.each{ |_,str| str.gsub! /^|$/, '%' }
my_hash.each{ |_,str| str.replace "%#{str}%" }

如果您希望哈希就地更改,但又不想影响字符串(您希望它获得新字符串):

If you want the hash to change in place, but you don't want to affect the strings (you want it to get new strings):

# Two ways to achieve the same result (any Ruby version)
my_hash.each{ |key,str| my_hash[key] = "%#{str}%" }
my_hash.inject(my_hash){ |h,(k,str)| h[k]="%#{str}%"; h }

如果你想要一个新的哈希:

If you want a new hash:

# Ruby 1.8.6+
new_hash = Hash[*my_hash.map{|k,str| [k,"%#{str}%"] }.flatten]

# Ruby 1.8.7+
new_hash = Hash[my_hash.map{|k,str| [k,"%#{str}%"] } ]

这篇关于在 Ruby 中更改散列中的每个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆