Space Vatican

Ramblings of a curious coder

Ruby Truth Serum

One of the joys of ruby is its flexibility – there are very few things set in stone. Occasionally this can make things hard to figure out. For example if someone has overridden the class method (not that uncommon when using proxies), then you can waste a lot of time wondering why something that claims to be an array isn’t quite behaving like one. Once you’ve established this, how would you find out what the real class of the object is?

I came across a neat trick today for dealing with this:

1
2
3
4
5
6
7
8
9
class Suspicious
  def self.class
    Array
  end
end

object = Suspicious.new
object.class #=> Array
Object.instance_method(:class).bind(object).call #=> Suspiscious

What we’re doing here is using Object’s implementation of the class method and calling it with the object we have at hand. Nifty