Ruby gsub 字符串中的多个字符 [英] Ruby gsub multiple characters in string
本文介绍了Ruby gsub 字符串中的多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 Ruby 1.9.3、Rails 3.2,我有以下内容:
Using Ruby 1.9.3, Rails 3.2, I have the following:
"every good boy does fine".gsub("every", "all").gsub("boy", "girl").gsub("fine", "well")
# => "all good girl does well"
有没有更好的方法来写这个?谢谢.
Is there a better way to write this? Thanks.
推荐答案
String#gsub
和 Hash#fetch
将是不错的选择.
String#gsub
and Hash#fetch
will be the good choice for this.
a = "every good boy does fine"
h = {"every" => "all","boy" => "girl", "fine" =>"well" }
a.gsub(/\w+/) { |m| h.fetch(m,m)}
# => "all good girl does well"
或者,
a = "every good boy does fine"
h = {"every" => "all","boy" => "girl", "fine" =>"well" }
Regexp.new("^#{h.keys.join('|')}$") # => /^every|boy|fine$/
a.gsub(Regexp.new("^#{h.keys.join('|')}$"),h)
# => "all good girl does well"
这篇关于Ruby gsub 字符串中的多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文