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

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

问题描述

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

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

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

要做到这一点的最佳方法是什么? 解决方案

如果您希望实际的字符串本身在适当位置进行变异(可能并希望影响对相同字符串对象的其他引用):

 #实现相同结果的两种方式(任何Ruby版本)
my_hash.each {| _,str | str.gsub! / ^ | $ /,'%'}
my_hash.each {| _,str | str.replace%#{str}%}

,但你不想影响字符串(你想它得到新的字符串):

 #两种实现方式相同的结果(任何Ruby版本)
my_hash.each {| key,str | my_hash [key] =%#{str}%}
my_hash.inject(my_hash){| h,(k,str)| H [K] = %#{STR}%; h}

如果你想要一个新的散列:

 #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}%]}]


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

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

must be changed to

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

What's the best way to do this?

解决方案

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天全站免登陆