All possible combinations of selected character substitution in a string in ruby

前端 未结 5 931
悲&欢浪女
悲&欢浪女 2020-12-18 11:07

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          


        
5条回答
  •  一生所求
    2020-12-18 11:40

    I'd do as follows using String#gsub(pattern, hash) :

    string = "this is a test"
    subs = {'a'=>'@','i'=>'!','s'=>'$'} # copied from @ArupRakshit
    keys = subs.keys
    

    And core code:

    1.upto(keys.length).flat_map { |i| 
      keys.combination(i).flat_map { |c| string.gsub(/[#{c.join}]/, subs) } 
    }
    

    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"]
    

提交回复
热议问题