Ruby中gsub字符串中的多个字符的疑问?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (11)

使用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","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"
用户回答回答于
replacements = [ ["every", "all"], ["boy", "girl"],["fine", "well"]
replacements.each {|replacement| str.gsub!(replacement[0], replacement[1])}

我不知道它是否更好,但更清洁。

扫码关注云+社区