Ruby多字符串替换 [英] Ruby multiple string replacement

查看:139
本文介绍了Ruby多字符串替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

str = "Hello☺ World☹"

预期输出为:

"Hello:) World:("

我可以这样做:str.gsub("☺", ":)").gsub("☹", ":(")

还有其他方法可以让我在单个函数调用中完成此操作吗?像这样:

Is there any other way so that I can do this in a single function call?. Something like:

str.gsub(['s1', 's2'], ['r1', 'r2'])

推荐答案

从Ruby 1.9.2开始,String#gsub接受哈希作为第二个参数,以替换为匹配的键.您可以使用正则表达式来匹配需要替换的子字符串,并为要替换的值传递哈希值.

Since Ruby 1.9.2, String#gsub accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.

赞:

'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"
'(0) 123-123.123'.gsub(/[()-,. ]/, '')    #=> "0123123123"

在Ruby 1.8.7中,您可以使用一个块来实现相同的目的:

In Ruby 1.8.7, you would achieve the same with a block:

dict = { 'e' => 3, 'o' => '*' }
'hello'.gsub /[eo]/ do |match|
   dict[match.to_s]
 end #=> "h3ll*"

这篇关于Ruby多字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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