M
Manoj Kumar
Can we see the singleton class as object in ruby.
Can we see the singleton class as object in ruby.
Jesús Gabriel y Galán said:Can we see the singleton class as object in ruby.
Like this?
irb(main):001:0> o = Object.new
=> #<Object:0xb743f3fc>
irb(main):002:0> singleton = class << o; self; end
=> #<Class:#<Object:0xb743f3fc>>
irb(main):003:0> singleton
=> #<Class:#<Object:0xb743f3fc>>
irb(main):004:0> def o.test; "test"; end
=> nil
irb(main):008:0> singleton.instance_methods(false)
=> ["test"]
Jesus.
Yes, and this method is now deprecated because of the wrong name.As you said =A0 class << o; self; end
In Rails, there is a method called metaclass which is defined in Object
def metaclass
=A0class << self
=A0 =A0self
=A0end
end
yes.=3D> # said:is #<Class:#<Object:0xb743f3fc>> the singleton class object for object
o?
Benoit said:Yes, and this method is now deprecated because of the wrong name.
The chosen name is ... singleton_class
So, the answer, in Ruby 1.9 is
yes.
B.D.
Benoit said:Yes, and this method is now deprecated because of the wrong name.
The chosen name is ... singleton_class
So, the answer, in Ruby 1.9 is
yes.
B.D.
Thanks Benoit.
If i try,
singleton.instance_methods(false), it is returning ["test"].
But, 'test' method is not available in singleton.methods. But it is
available in singleton.instance_methods.
Why it is like this? Any special reason for this?
Jesús Gabriel y Galán said:available in singleton.instance_methods.
Why it is like this? Any special reason for this?
Because methods returns the list of methods that are accessible for
the object. In the case of the singleton class, it's the instance of
the class (the object) for which you call the method "test". It's the
same thing as with regular classes:
irb(main):001:0> class A
irb(main):002:1> def test
irb(main):003:2> "test"
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> A.methods.grep(/test/)
=> []
irb(main):007:0> A.instance_methods.grep(/test/)
=> ["test"]
irb(main):008:0> a = A.new
=> #<A:0xb74d2274>
irb(main):009:0> a.methods.grep(/test/)
=> ["test"]
Jesus.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.