Hello,
This is my first post at ruby-talk
I’m a some year exprience of rubyist without deep understanding
Now I’m trying to understand more about meta programming.
I browsed other people’s sources and have a question.
What does (class << self; self; end) means ?
I did an experience like this.
#!/usr/bin/ruby
class Cat
def self.mew
p self
p (class << self; self; end)
end
end
Cat.mew
The output was
Cat
#Class:Cat
I think the latter( #Class:Cat ) means Class singleton object.
Moreover, from my understanding I’ve been thinking that the former also
means Class singleton object.
Could you please tell the difference between self and (class << self;
self; end) in the context ?
Thank you,
Toshi U. now @Tokyo, soon @Atlanta
On Wed, Jun 18, 2014 at 4:41 PM, Toshi U. [email protected]
wrote:
Could you please tell the difference between self and (class << self; self;
end) in the context ?
class << X
opens the singleton class of object X, whatever that is. X could be a
normal object or a class or whatever. Inside that scope, “self” means
the object that is the singleton class of X.
So,
class Cat
def self.mew
class << self
opens the scope of the singleton class of the object that happens to
be self at that point. As you are in a class instance method, self is
the object Cat (the class object, remember that classes are objects
too). So,
class Cat
def self.mew # this creates a class instance method
p self # here, self is the Cat class object (classes are objects
too)
class << self
self # this self is the singleton class of the previous line
self, which is the Cat class, so: singleton class of Cat
end
end
end
The interesting thing is that when you define a class instance method,
it’s actually defined in the singleton class of Cat. So, mew is an
instance method of #Class:Cat
2.0.0p195 :010 > class << Cat; p instance_methods.grep(/mew/); end
[:mew]
Jesus.
Thank you , Jes??s Gabriel y Gal??n
class << X
opens the singleton class of object X, whatever that is. X could be a
normal object or a class or whatever.
This explains all !
I read the book, “Metaprogramming Ruby” again and I could understand
your words.
Thanks.
Toshi,
You should be aware that the:
class <<self
self
end
dance got a little wearisome, so now ruby has a method to do that:
class Cat
class <<self
p self
end
p self.singleton_class
end
p Cat.singleton_class
–output:–
#Class:Cat
#Class:Cat
#Class:Cat
I read the book, “Metaprogramming Ruby” again and I could
understand your words.
Reviewing “Metaprogramming Ruby” now and again is very worthwhile.