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

前端 未结 5 934
悲&欢浪女
悲&欢浪女 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:41

    string = "this is a test"
    subs = ['a'=>'@','i'=>'!','s'=>'$']
    
    subs = subs.first.map(&:to_a)
    1.upto(subs.length).each do |n|
      subs.combination(n).each do |a|
        p a.each_with_object(string.dup){|pair, s| s.gsub!(*pair)}
      end
    end
    

提交回复
热议问题