Class: Parsey::ScanArray

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

Overview

ScanArray is an array of tokens created when scanning the pattern. It looks like this:

[[:block, 'what-'], [:optional, [[:text, "hi-"]]], [:text, "oh"]]

Instance Method Summary collapse

Instance Method Details

#each_with_type {|Symbol, Object| ... } ⇒ StringScanner

Loops through the types and contents of each tag separately, passing them to the block given.

Examples:


sa = ScanArray.new([[:text, 'hey-'], 
                    [:optional, 
                      [[:block, '([a-z]+)'], 
                       [:text, '-what']]
                   ]])

sa.each_with_type do |type, content|
  puts "#{type} -> #{content}"
end
#=> text -> hey-
#=> optional -> [[:block, "([a-z]+)"], [:text, "-what"]]

Yields:

  • (Symbol, Object)

    gives the type and content of each block in turn

Returns:

  • (StringScanner)

    returns self



295
296
297
298
299
300
301
302
# File 'lib/parsey.rb', line 295

def each_with_type(&blck)
  ts = self.collect {|i| i[0]}
  cs = self.collect {|i| i[1]}
  (0...ts.size).each do |i|
    yield(ts[i], cs[i])
  end
  self
end

#each_with_type_indexed {|Symbol, Object Integer| ... } ⇒ Object

Yields:

  • (Symbol, Object Integer)

    gives the type, content and index of each block in turn

See Also:



306
307
308
309
310
311
312
313
# File 'lib/parsey.rb', line 306

def each_with_type_indexed(&blck)
  ts = self.collect {|i| i[0]}
  cs = self.collect {|i| i[1]}
  (0...ts.size).each do |i|
    yield(ts[i], cs[i], i)
  end
  self
end

#flattenArray

Removes all :text nodes from pat and puts :optional nodes contents’ into the main array, and puts a nil in place

Examples:


sa = ScanArray.new([[:text, 'hey-'], 
                    [:optional, 
                      [[:block, '([a-z]+)'], 
                       [:text, '-what']]
                   ]])

sa.flatten
  #=> [[:optional, nil], [:block, "([a-z]+)"]]

Returns:

  • (Array)


248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/parsey.rb', line 248

def flatten
  # Flatten the array with Array#flatten before starting
  flat = super
  
  indexes = []
  flat.each_with_index do |v, i|
    if v == :optional
      indexes << i
    end
  end
  
  # Need to start from the back so as not to alter the indexes of the 
  # other items when inserting
  indexes.reverse.each do |i|
    flat.insert(i+1, nil)
  end
  
  flat.reverse!
  r = ScanArray.new
  while flat.size > 0
    r << [flat.pop, flat.pop]
  end
  
  r.delete_if {|i| i[0] == :text}
  r
end

#flatten!Object

See Also:



228
229
230
# File 'lib/parsey.rb', line 228

def flatten!
  self.replace(self.flatten)
end