New to programming and to Ruby, and I hope this question about symbols is in line. I understand that symbols in Ruby (e.g., :book
, :price
) are usef
(Answer to your comment)
dog = 'dog'
or String.new("dog")
After dog = String.new, the field class of instance dog points to class String.
class << dog
puts "inside #{self}" #=> inside #>
def bark
puts 'woof'
end
end
dog.bark #=> "woof"
p dog.singleton_methods #=> ["bark"]
With class << dog
or def dog.bark
, Ruby creates an anonymous class, the field class of instance dog now points to this anonymous class, and from there to String. Methods defined in this context with def or define_method go into the methods table of the anonymous class.
Ruby 1.9.2 has introduced Object#singleton_class. [The Pickaxe] Returns the singleton class of obj, creating one if necessary. (I add) It is equivalent to class << self; self end
.
The Ruby Programming Language (O'Reiily) simply says : to open the eigenclass [singleton class] of the object o, use class << o.
So I don't know how to read it loud. I have read that some would prefer o >> class
. It's only recently that I have found how to figure out what this strange expression means. I pronounce : go from o to it's anonymous class.
class << MyClass
def dog
puts 'dog as class method'
end
end
MyClass.dog #=> dog as class method
The same is true for a class. With class MyClass
, MyClass, as instance of Class, is an object with a pointer to its class Class. With def MyClass.some_method
or class << MyClass
, Ruby creates an anonymous class which is inserted between MyClass and Class, and class methods go into it.
Maybe something like: "from class, instantiate singleton object self
Yes for "from class/object" to anonymous singleton class/eigenclass/metaclass.
But we don't instantiate self. Self (in Smaltalk, this in C++/Java) is kind of a reserved word which designate the receiver of the message. dog.bark
: in OO language we say that the message bark in sent to object dog. Inside the method bark
, self will be set to dog, so that we can reference dog. This is more obvious with
o1 = MyClass.new; o2 = MyClass.new
o1.some_method; o2.some_method
some_method must be able to reference the receiver in a generic way, is it o1 or o2, this is what self is for.