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

标签 ruby string combinations substitution gsub

我想知道是否有一种简单的方法可以用一种简单的方式在 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/

相关文章:

algorithm - 用给定的橙子和苹果制作水果篮的所有组合

Ruby:使用gsub有条件地替换字符串

c++ - 基于c++中的多个字符串分隔符拆分字符串

algorithm - 有多少个数字包含给定的数字?

php - 如何将 [link](#) 替换为 <a href ="#">link</a>?

android - 使用 String 上的蓝牙地址连接到设备

angular - q.all for angular2 observables

mysql - 如何给 "push ahead"记录一个给定的值?

ruby-on-rails - Redis-To-Go 难度 - getaddrinfo : nodename nor servname provided, 或未知,Rails 4

ruby-on-rails - 将 bool 值设置为 false