Class: Peggy::Multiple

Inherits:
Element show all
Includes:
OneChild
Defined in:
lib/parse/builder.rb

Overview

An element which tries its single child multiple times. It is greedy, meaning it will continue to match as long as possible, unless the range specifies a maximum number of matches.

Direct Known Subclasses

AnyNumber, AtLeastOne, Optional

Constant Summary collapse

MANY =

A big number

32767

Instance Attribute Summary collapse

Attributes included from OneChild

#child

Instance Method Summary collapse

Methods included from OneChild

#wrap

Methods inherited from Element

build, #report

Constructor Details

#initialize(range) ⇒ Multiple

Init the range



122
123
124
# File 'lib/parse/builder.rb', line 122

def initialize range
  @range = range
end

Instance Attribute Details

#rangeObject

The minimum and maximum number of tries



119
120
121
# File 'lib/parse/builder.rb', line 119

def range
  @range
end

Instance Method Details

#match(parser, index) ⇒ Object

Matches the child multiple times. The range specifies the least and most number of matches. If the number of matches is less than the minimim of the range then NO_MATCH is returned. If equal or more than the minimim then the end index of the last match is returned.



129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/parse/builder.rb', line 129

def match parser, index
  raise "multiple element child not set" unless child
  raise "multiple element range not set" unless range
  count = 0
  while count < range.last
    found = child.match parser, index
    break unless found
    index = found
    count += 1
  end
  report range === count ? index : NO_MATCH
end

#to_sObject

Convert element to String.



143
144
145
# File 'lib/parse/builder.rb', line 143

def to_s
  "#{wrap}{#{range.min}..#{range.max}}"
end