Module: Permutations::String

Included in:
String
Defined in:
lib/permutations.rb

Instance Method Summary collapse

Instance Method Details

#permutations(separator = ',', escape_separator = true) ⇒ Object

Create multi-level string permutations “a,b,c1,2,3”.permutations # => [“a1”, “a2”, “a3”, “b1”, “b2”, “b3”, “c1”, “c2”, “c3”]



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/permutations.rb', line 20

def permutations(separator=',', escape_separator=true)
  separator=Regexp.escape(separator) if escape_separator
  matches = self.scan(/(\{\s*(.*?)\s*\})/)
  substitutions = matches.map{|match| match[0]}
  permutations = matches.map{|match| match[1].split(/\s*#{separator}\s*/)}.permutations
  permutations.map do |permutation|
    permutated_string = self.dup
    permutation.each_with_index do |choice, index|
      choice_string = substitutions[index]
      permutated_string.sub!(choice_string,choice)
    end
    permutated_string
  end
end