ruby-on-rails – Ruby gsub字符串中的多个字符

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Ruby gsub字符串中的多个字符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用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#gsubHash#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"

猜你在找的Ruby相关文章