views:

74

answers:

2

Normally, I might get the metaclass for a particular instance of a Ruby object with something like this:

class C
  def metaclass
    class << self; self; end
  end
end

# This is this instance's metaclass.
C.new.metaclass => #<Class:#<C:0x01234567>>

# Successive invocations will have different metaclasses,
# since they're different instances.
C.new.metaclass => #<Class:#<C:0x01233...>>
C.new.metaclass => #<Class:#<C:0x01232...>>
C.new.metaclass => #<Class:#<C:0x01231...>>

Let's say I just want to know the metaclass of an arbitrary object instance obj of an arbitrary class, and I don't want to define a metaclass (or similar) method on the class of obj.

Is there a way to do that?

+3  A: 

Yep.

metaclass = class << obj; self; end

x1a4
Small typo: I think you meant `class << obj`, not `@obj`.
John Feminella
yes, fixed. thanks.
x1a4
I knew I was missing the obvious syntax. Thank you very much!
Stanislaus Wernstrom
+2  A: 

The official name in singleton_class. The way to get it (in Ruby 1.9.2) is simply:

obj.singleton_class

For older Ruby versions, either require 'backports' and call obj.singleton_class, or else use class << obj; self; end.

Marc-André Lafortune