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

时间:2014-03-02 17:51:20

标签: ruby

我正在使用this answer中的代码,但是如果我想做多个选项来说出你将在下面看到的“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

1 个答案:

答案 0 :(得分:1)

而不是您的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 !s a 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"