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

use*_*038 2 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 ")
Run Code Online (Sandbox Code Playgroud)

Lin*_*ios 5

您可以使用哈希:

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

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

body.gsub!(/(?=\b).+(?=\b)/) {|m| subs[m]}
Run Code Online (Sandbox Code Playgroud)


ste*_*lag 5

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)
Run Code Online (Sandbox Code Playgroud)