32 11 51 10 = Object - State (instance variables) - Behaviour (methods) = Me, me, me First, understand self ... self is the "current object" - Default receiver for method calls with no receiver - Place where instance variables are kept self always has a meaningful value in Ruby == What changes self? - method call - class definition === On method call receiver.method(params) - switch self to receiver - Look up method in self's class (and up the chain) - Invoke method The first thing Ruby does when you call a method, is to change self When calling a method, we go one to the right, and then up class Dave def first @iv = "wibble" second end def second puts @iv end end If you get confused when you do meta-programming, draw pictures If you draw pictures, do it consistent When you define a singleton method, an anonymous class is created by Ruby and inserted between it and it's parents class But if you ask the object it will say that it's parent is still the original parent p is an alias for puts my_object.inspect === Class definition Inside a class definition, Ruby sets self to be that particular class Classes are objects I don't have a class called Dave, but a constant, that has a reference to the class called Dave (which is an instance of the Class class) Classes are not magic things, they are just contants that holds objects ==== Class methods self. syntax is marginally safer in obscure instances With class methods an anonymous class is also constructed - just like with singleton methods on any other object Ruby does not have class methods/static methods. All it has is methods, and it nows where to put them. == Summary instance variables are always looked up in self methods are always looked up in self.class = The class << self syntax class << animal Sets self to be the object on the right-hand side Puts methods into the singleton class = Wrongly for newcomers class Dave # Will be a class object, instead of an instance object @fred = "smith" end To make "static" attributes we just do class Dave class << self attr_read :fred end end = Inheritance class Thomas < Dave end Dave doesn't have to be a constant class Person < Struct.new(:name, :country) end = Last fantastic thing module Logger def log(msg) STDERR.puts msg end end class Dave include Logger end d = Dave.new d.log("hello") Understanding what module inclusion does, is really critical When you create a Module, you get an object