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"

相关文章

以下代码导致我的问题: class Foo def initialize(n=0) @n = n end attr_accessor :n d...
这是我的spec文件,当为上下文添加测试“而不是可单独更新用户余额”时,我得到以下错误. require 's...
我有一个拦截器:DevelopmentMailInterceptor和一个启动拦截器的inititializer setup_mail.rb. 但我想将...
例如,如果我有YAML文件 en: questions: new: 'New Question' other: recent: ...
我听说在RSpec中避免它,let,let !,指定,之前和主题是最佳做法. 关于让,让!之前,如果不使用这些,我该如...
我在Rails中使用MongoDB和mongo_mapper gem,项目足够大.有什么办法可以将数据从Mongoid迁移到 Postgres...