From: Manoj Kumar on
Can we see the singleton class as object in ruby.
--
Posted via http://www.ruby-forum.com/.

From: Jesús Gabriel y Galán on
On Fri, Jun 25, 2010 at 6:11 AM, Manoj Kumar <manojs.nitt(a)gmail.com> wrote:
> 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.

From: Manoj Kumar on
Hi Jesus,

Thanks for your reply.


class Sample

def in_class
'in_class'
end

end

@sample = Sample.new

@sample.instance_eval do

def in_singleton
'in singleton'
end

end


In @sample object, in_class method will be available in Sample class.

But in_singleton method will be available in sinlgeton class of @sample.

That singleton class will be available in memory.

But i couldn't see that class in the form of object or some thing else.


Thanks,

Manoj
--
Posted via http://www.ruby-forum.com/.

From: Manoj Kumar on
Jesús Gabriel y Galán wrote:
> On Fri, Jun 25, 2010 at 6:11 AM, Manoj Kumar <manojs.nitt(a)gmail.com>
> wrote:
>> 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.

As you said class << o; self; end

In Rails, there is a method called metaclass which is defined in Object

def metaclass
class << self
self
end
end

is #<Class:#<Object:0xb743f3fc>> the singleton class object for object
o?
--
Posted via http://www.ruby-forum.com/.

From: Benoit Daloze on
On 27 June 2010 16:43, Manoj Kumar <manojs.nitt(a)gmail.com> wrote:
> As you said   class << o; self; end
>
> In Rails, there is a method called metaclass which is defined in Object
>
> def metaclass
>  class << self
>    self
>  end
> end
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
> > "mystr".singleton_class
=> #<Class:#<String:0x00000100864fd8>>

> is #<Class:#<Object:0xb743f3fc>> the singleton class object for object
> o?
yes.

B.D.