Class: PatternRandomizer

Inherits:
Object
  • Object
show all
Defined in:
lib/pattern_randomizer.rb

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ PatternRandomizer

Returns a new instance of PatternRandomizer.



2
3
4
# File 'lib/pattern_randomizer.rb', line 2

def initialize(pattern)
  @pattern = pattern
end

Instance Method Details

#to_sObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pattern_randomizer.rb', line 6

def to_s
  stack = []
  stack_depth = 0

  @pattern.scan(/\(|\)|\||[^\(\)\|]+/) do |token|
    # puts "stack is: #{stack.inspect}, token is: #{token.inspect}"
    case token
    when '('
      stack_depth += 1
      stack.push '('
    when ')'
      stack_depth -= 1
      if stack_depth < 0
        raise 'Unbalanced brackets'
      end
      close_bracket(stack)
    when '|'
      stack.push '|'
    else
      stack.push token
    end
  end

  stack.join
end