Class: Baba::Environment
- Inherits:
-
Object
- Object
- Baba::Environment
- Defined in:
- lib/baba/environment.rb
Instance Attribute Summary collapse
-
#enclosing ⇒ Object
readonly
Returns the value of attribute enclosing.
-
#values ⇒ Object
readonly
Returns the value of attribute values.
Instance Method Summary collapse
- #[](name) ⇒ Object
- #[]=(name, value) ⇒ Object
- #ancestor(distance) ⇒ Object
- #assign_at(distance, name, value) ⇒ Object
- #define(name, value) ⇒ Object
- #get_at(distance, name) ⇒ Object
-
#initialize(enclosing = nil) ⇒ Environment
constructor
A new instance of Environment.
Constructor Details
#initialize(enclosing = nil) ⇒ Environment
Returns a new instance of Environment.
7 8 9 10 |
# File 'lib/baba/environment.rb', line 7 def initialize(enclosing = nil) @enclosing = enclosing @values = {} end |
Instance Attribute Details
#enclosing ⇒ Object (readonly)
Returns the value of attribute enclosing.
5 6 7 |
# File 'lib/baba/environment.rb', line 5 def enclosing @enclosing end |
#values ⇒ Object (readonly)
Returns the value of attribute values.
5 6 7 |
# File 'lib/baba/environment.rb', line 5 def values @values end |
Instance Method Details
#[](name) ⇒ Object
33 34 35 36 37 38 39 40 41 |
# File 'lib/baba/environment.rb', line 33 def [](name) if @values.include?(name.lexeme) return @values[name.lexeme] end return @enclosing[name] unless @enclosing.nil? raise BabaRuntimeError.new(name, "Undefined variable '#{name.lexeme}'.") end |
#[]=(name, value) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/baba/environment.rb', line 43 def []=(name, value) if @values.include?(name.lexeme) @values[name.lexeme] = value return end unless @enclosing.nil? @enclosing[name] = value return end raise BabaRuntimeError.new(name, "Undefined variable '#{name.lexme}'.") end |
#ancestor(distance) ⇒ Object
16 17 18 19 20 21 22 23 |
# File 'lib/baba/environment.rb', line 16 def ancestor(distance) environment = self 1.upto(distance) do environment = environment.enclosing end environment end |
#assign_at(distance, name, value) ⇒ Object
29 30 31 |
# File 'lib/baba/environment.rb', line 29 def assign_at(distance, name, value) ancestor(distance).values[name.lexeme] = value end |
#define(name, value) ⇒ Object
12 13 14 |
# File 'lib/baba/environment.rb', line 12 def define(name, value) @values[name] = value end |
#get_at(distance, name) ⇒ Object
25 26 27 |
# File 'lib/baba/environment.rb', line 25 def get_at(distance, name) ancestor(distance).values[name] end |