I was wondering if there is a simple way to do every combination of selected character substitutions in ruby in a simple way.
An example:
string = "this is a test"
subs = ['a'=>'@','i'=>'!','s'=>'$']
subs.combination.each { |c|
string.gsub c
}
would yield
"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"
Thanks for the help!
I'd do as below :
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
output
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With