使用Ruby 1.9.3,Rails 3.2,我有以下几点:
"every good boy does fine".gsub("every","all").gsub("boy","girl").gsub("fine","well") # => "all good girl does well"
有没有更好的方法来写这个?谢谢.
解决方法
String#gsub
和
Hash#fetch
将是不错的选择.
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","fine" =>"well" } Regexp.new("^#{h.keys.join('|')}$") # => /^every|boy|fine$/ a.gsub(Regexp.new("^#{h.keys.join('|')}$"),h) # => "all good girl does well"