我可以在Ruby中使用gsub和Hashes吗?

时间:2013-07-20 20:05:36

标签: ruby hash gsub

我想通过我的输入并用Ruby中的300对反义词替换单词。

在Python中,创建字典是一种有效的方法,使用replace进行比较。

在Ruby中,如果我逐行使用gsub!,它是否比使用哈希效率低得多?如果我只有300对,它会有所作为吗?

body=ARGV.dup

body.gsub!("you ","he ")
body.gsub!("up","down ")
body.gsub!("in ","out ")
body.gsub!("like ","hate ")
body.gsub!("many ","few ")
body.gsub!("good ","awesome ")
body.gsub!("all ","none ")

2 个答案:

答案 0 :(得分:5)

您可以使用哈希:

subs = {
  "you" => "he",
  etc.
}
subs.default_proc = proc {|k| k}
body.gsub(/(?=\b).+(?=\b)/, subs)

如果为了提高效率,您需要gsub!,请使用:

body.gsub!(/(?=\b).+(?=\b)/) {|m| subs[m]}

答案 1 :(得分:3)

subs = {
  "you" => "he",
  "up" => "down",
  "in" => "out"}

# generate a regular expression; 300 keys is fine but much more is not.
re = Regexp.union(subs.keys)

p "you are in!".gsub(re, subs)
# => "he are out!"

body.gsub(re, subs)