Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I get the class of a BasicObject instance?
    text
    copied!<p>I have a script that iterates using <code>ObjectSpace#each_object</code> with no args. Then it prints how many instances exist for each class. </p> <p>I realized that some classes redefine the <code>#class</code> instance method, so I had to find another way to get the actual class; Let's say it's stored in variable <code>"klass"</code>, and <code>klass === object</code> is true.</p> <p>In Ruby 1.8 I could do this, assuming <code>Object</code> wasn't monkeypatched:</p> <pre><code>Object.instance_method(:class).bind(object).call </code></pre> <p>This worked for <code>ActiveSupport::Duration</code> instances:</p> <pre><code># Ruby 1.8 # (tries to trick us) 20.seconds.class =&gt; Fixnum # don't try to trick us, we can tell Object.instance_method(:class).bind(20.seconds).call =&gt; ActiveSupport::Duration </code></pre> <p>But, in Ruby 1.9 this no longer works:</p> <pre><code># Ruby 1.9 # we are not smart... Object.instance_method(:class).bind(20.seconds).call TypeError: bind argument must be an instance of Object from (irb):53:in `bind' from (irb):53 from /Users/user/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `&lt;main&gt;' </code></pre> <p>It turns out that <code>ActiveSupport::Duration</code> subclasses <code>ActiveSupport::BasicObject</code>. The latter is made to subclass <code>::BasicObject</code> in Ruby 1.9, so <code>Object</code> is excluded from the inheritance chain. This doesn't, and can't, happen in Ruby 1.8, so <code>ActiveSupport::BasicObject</code> is a subclass of <code>Object</code>.</p> <p>I haven't found any way to detect the actual class of a Ruby 1.9 object that isn't an instance of <code>Object</code>. <code>BasicObject</code> in 1.9 is really bare-bones:</p> <pre><code>BasicObject.instance_methods =&gt; [:==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__] </code></pre> <p>Ideas?</p> <p>UPDATE:</p> <p>Since ruby 1.9 reached end-of-life, I'm changing my accept to @indirect's answer. The mentions of ruby 1.9 above are merely for historical purposes, to show that the change from 1.8 to 1.9 was the original cause of my problem.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload