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

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 に答える