Class: Soroban::ValueWalker

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/soroban/value_walker.rb

Overview

An enumerable that allows values of cells in a range to be visited.

Instance Method Summary collapse

Constructor Details

#initialize(range, context) ⇒ ValueWalker

Create a new walker from a supplied range and binding. The binding is required when calculating the value of each visited cell.



13
14
15
16
# File 'lib/soroban/value_walker.rb', line 13

def initialize(range, context)
  @_range, @_binding = range, context
  @_labels = Soroban::LabelWalker.new(range).to_a
end

Instance Method Details

#[](index) ⇒ Object

Get the value of a cell within the range by index. Will raise a RangeError if the index is outside of the range.



25
26
27
28
29
30
# File 'lib/soroban/value_walker.rb', line 25

def [](index)
  if index < 0 || index >= @_labels.length
    raise Soroban::RangeError, "Index #{index} falls outside of '#{@_range}'"
  end
  eval("get('#{@_labels[index]}')", @_binding)
end

#[]=(index, value) ⇒ Object

Set the value of a cell within the range by index. Will raise a RangeError if the index is outside of the range.



34
35
36
37
38
39
40
# File 'lib/soroban/value_walker.rb', line 34

def []=(index, value)
  if index < 0 || index >= @_labels.length
    raise Soroban::RangeError, "Index #{index} falls outside of '#{@_range}'"
  end
  eval("@#{@_labels[index]}.set('#{value}')", @_binding)
  return value
end

#eachObject

Yield the value of each cell referenced by the supplied range.



19
20
21
# File 'lib/soroban/value_walker.rb', line 19

def each
  @_labels.each { |label| yield eval("get('#{label}')", @_binding) }
end

#to_sObject Also known as: inspect

Display the range if the user outputs the binding directly



43
44
45
# File 'lib/soroban/value_walker.rb', line 43

def to_s
  @_range
end