Class: Baba::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/baba/instance.rb

Direct Known Subclasses

RubyObject

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Instance

Returns a new instance of Instance.



5
6
7
8
# File 'lib/baba/instance.rb', line 5

def initialize(klass)
  @klass = klass
  @fields = {}
end

Instance Method Details

#[](name) ⇒ Object

Raises:



10
11
12
13
14
15
16
17
18
19
# File 'lib/baba/instance.rb', line 10

def [](name)
  if @fields.include?(name.lexeme)
    return @fields[name.lexeme]
  end

  method = @klass.find_method(name.lexeme)
  return method.bind(self) unless method.nil?

  raise BabaRuntimeError.new(name, "Undefined property #{name.lexeme}.")
end

#[]=(name, value) ⇒ Object



21
22
23
# File 'lib/baba/instance.rb', line 21

def []=(name, value)
  @fields[name.lexeme] = value
end

#inspectObject



33
34
35
# File 'lib/baba/instance.rb', line 33

def inspect
  to_s
end

#to_sObject



25
26
27
28
29
30
31
# File 'lib/baba/instance.rb', line 25

def to_s
  base_string = "<#{@klass.name} instance:"
  @fields.each do |field, value|
    base_string += " #{field} => #{value}"
  end
  base_string += ">"
end