我想知道是否有一种简单的方法可以用一种简单的方式在 ruby 中完成所选字符替换的每种组合。
一个例子:
string = "this is a test"
subs = ['a'=>'@','i'=>'!','s'=>'$']
subs.combination.each { |c|
string.gsub c
}
会产生
"this is @ test"
"th!s !s a test"
"thi$ i$ a te$t"
"th!s !s @ test"
"thi$ i$ @ te$t"
"th!$ !$ a te$t"
"th!$ !$ @ te$t"
感谢您的帮助!
最佳答案
我会做如下:
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
输出
this is @ test
th!s !s a test
thi$ i$ a te$t
th!s !s @ test
thi$ i$ @ te$t
th!$ !$ a te$t
th!$ !$ @ te$t
关于ruby - ruby 字符串中选定字符替换的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22067184/