2

我想检查我的输入并用 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 ")
4

2 回答 2

5

您可以使用哈希:

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

如果,为了提高效率,你需要gsub!,使用这个:

body.gsub!(/(?=\b).+(?=\b)/) {|m| subs[m]}
于 2013-07-20T20:19:21.107 回答
4
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)
于 2013-07-20T22:54:08.673 回答