Class: Capture::TableCapture

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

Overview

The result of a table capture. The idea is to mimic a little bit of the functionality of a Lua table which is like a combination Array/Hash.

Internally, we have a hash. Indexing can be by (hash) key or (array) index. Getting and setting is supported.

The initial, contiguous segment of the array part (non nil values at 0, 1, 2, …, k) is available from #unpack.

Defined Under Namespace

Modules: ArrayHashOverloadExtension

Instance Method Summary collapse

Constructor Details

#initialize(hash_part, array_part) ⇒ TableCapture

Returns a new instance of TableCapture.



55
56
57
58
59
60
# File 'lib/rpeg/captures.rb', line 55

def initialize(hash_part, array_part)
  @data = hash_part.clone
  array_part.each_with_index do |val, idx|
    @data[idx] = val
  end
end

Instance Method Details

#==(other) ⇒ Object

We support comparison with

  • TableCapture, in which case we just compare the data objects

  • Hash, in which case we check key-by-key

  • Array, in which case we check index-by-index



96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/rpeg/captures.rb', line 96

def ==(other)
  case other
  when TableCapture
    @data == other.instance_variable_get(:@data)
  when Hash
    @data == other
  when Array
    @data == other.each_with_index.to_a.map(&:reverse).to_h
  else
    raise "Bad type #{other.class} for =="
  end
end

#[](key) ⇒ Object



80
81
82
# File 'lib/rpeg/captures.rb', line 80

def [](key)
  @data[key]
end

#[]=(key, value) ⇒ Object



84
85
86
# File 'lib/rpeg/captures.rb', line 84

def []=(key, value)
  @data[key] = value
end

#delete(key) ⇒ Object



88
89
90
# File 'lib/rpeg/captures.rb', line 88

def delete(key)
  @data.delete(key)
end

#eachObject



67
68
69
# File 'lib/rpeg/captures.rb', line 67

def each
  @data.each
end

#empty?Boolean

Note that we say false if all keys are positive integers but 0 has no value (and so #unpack returns [])

Returns:

  • (Boolean)


72
73
74
# File 'lib/rpeg/captures.rb', line 72

def empty?
  size.zero?
end

#sizeObject



76
77
78
# File 'lib/rpeg/captures.rb', line 76

def size
  @data.size
end

#unpackObject

Let i be the smallest natural number such that self.nil?. We return [self, self, …, self]



63
64
65
# File 'lib/rpeg/captures.rb', line 63

def unpack
  (0..).lazy.map { |key| @data[key] }.take_while { |v| !v.nil? }.force
end