Method: Parsey::ScanArray#flatten

Defined in:
lib/parsey.rb

#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