Some definitions
- Containers Hashes whose keys are Symbols
- Pointers Fixnum whose value is a location in memory
There are 4 things in the Ruby Object Model:
- Classes
- Container for methods
- Pointer to the superclass
- These are also objects
- Objects
- Container for Instance variables
- Pointer to the class
- Bindings
- Container for Local variables
- Pointer to self
- Pointer to return value ;)
- Stack
- A Linked list (or an array) of bindings
What is self for?
- When we call a method without a receiver, we call it on self
- It's where we get or set instance variable
- Explicitly referencing self
https://gist.github.com/JoshCheek/ad9f70a6d855be9ed50d
We did lines 20-200 in class.
Method lookup... I could write it in human words, but it seems easier to write it in code :)
# find the method
current_class = object.class
until current_class.instance_methods[method_name]
current_class = current_class.superclass
break unless current_class
end
# make sure we found it
unless current_class
raise NoMethodError, method_name
end
# invoke it
stack.push Binding.new(self: object, local_variables: arguments)
# How might I put a method on one specific object?
class Robot
def self.new(name)
robot = self.allocate()
robot.__send__ :initialize, name # => "Carl", "Ellie", "Stacy"
robot
end
attr_accessor :name
def initialize(name)
@name = name # => "Carl", "Ellie", "Stacy"
end
def dance!
"The Robot Dance"
end
def beep
'boop'
end
end
# DANCE CONTEST!
carl = Robot.new 'Carl' # => #<Robot:0x007ffbc405fba0 @name="Carl">
ellie = Robot.new 'Ellie'
stacy = Robot.new 'Stacy'
class << ellie
def dance!
'Fancy Dance'
end
end
def stacy.dance!
"Maccarena and #{super}"
end
carl.dance! # => "The Robot Dance"
ellie.dance! # => "Fancy Dance"
stacy.dance! # => "Maccarena and The Robot Dance"
carl.name # => "Carl"
ellie.name # => "Ellie"
stacy.name # => "Stacy"
# A module is a bag of methods, just like a class
# When you include it into a class, it makes a new "included class"
# and places that into the inheritance hierarchy.
# It sets the included class' methods to point at the module's methods
# So, where you can only have one superclass,
# you can have any number of included classes
module Lol
def lol; 'lol!' end
end
module Wtf
def wtf; 'wtf' end
end
class A
include Lol
end
class B
include Lol
include Wtf
end
class C
include Wtf
end
A.new.lol # => "lol!"
B.new.lol # => "lol!"
B.new.wtf # => "wtf"
C.new.wtf # => "wtf"