How does self work, and what is the difference between class and instance methods?
self is the current object. Inside an instance method it is the receiver, inside a class body it is the class, and inside a class method it is the class as well.
class Widget
def initialize(name)
@name = name
end
def self.default
new("default") # class method
end
class << self
def count
@count ||= 0 # class-level instance variable
end
end
end
Widget.default
Defining def self.foo adds a singleton method to the class object, so it is called on the class rather than an instance. Instance variables differ by context: @name in an instance method belongs to the instance, while @count in a class method belongs to the class object.
self is also required to call an attribute writer, as in self.name = value, because a bare name = value would create a local variable instead.