ruby中字符串中所选字符替换的所有可能组合 – 改进

我正在使用这个答案中的代码,但如果我想做多个选项来说出你将在下面看到的“s”替换,它只能处理一个。 如何使下面的代码更换为这样的代码:

subs = {'a'=>['@'],'i'=>['!'],'s'=>['$','&'] } 

这是原始代码和替换。

 string = "this is a test" subs = {'a'=>'@','i'=>'!','s'=>'$'} keys = subs.keys combinations = 1.upto(subs.size).flat_map { |i| keys.combination(i).to_a } combinations.each do |ary| new_string = string.dup ary.each { |c| new_string.gsub!(c,subs) } puts new_string end 

而不是你的subs ,下面的一个,包括替换可以空洞应用的信息,将更容易处理:

 subs = {"a" => ["a", "@"], "i" => ["i", "!"], "s" => ["s", "$", "&"]} 

使用这个,你应该坚持我的答案。 以下只是对我之前问题的答案的一个小修改:

 string = "this is a test" a = subs.values a = a.first.product(*a.drop(1)) a.each do |a| p [subs.keys, a].transpose.each_with_object(string.dup){|pair, s| s.gsub!(*pair)} end 

这使:

 "this is a test" "thi$ i$ a te$t" "thi& i& a te&t" "th!s !sa test" "th!$ !$ a te$t" "th!& !& a te&t" "this is @ test" "thi$ i$ @ te$t" "thi& i& @ te&t" "th!s !s @ test" "th!$ !$ @ te$t" "th!& !& @ te&t"