Sneaky Abstractions

Subscribe to my Feed, follow me on , recommend me on Working With Rails or see my code on GitHub

Prototype-based inheritance in Ruby

Posted on June 06, 2007 16:59 Tagged with ruby.

This was originally posted as a response to a “challenge” on irb.no, and I thought it was kind of clever, so I’ll post it here as well ;) The challenge was to write something object-oriented in Ruby without using classes. So, inspired by my recent crush on ECMAScript, I thought, why not try to implement prototype-based inheritance in Ruby?

Object.class_eval{ attr_accessor :prototype }
Object.class_eval do
  def method_missing(s, *a)
    if self.prototype.nil?
      raise NoMethodError, "LOL U MISSING #{s}!!"
    else
      self.prototype.send(s, *a)
    end
  end
end

cat = Object.new
def cat.meow; 'IM IN UR OBJECTZ'; end
cat.meow # => "IM IN UR OBJECTZ"
kitten = Object.new
kitten.prototype = cat
kitten.meow # => "IM IN UR OBJECTZ"

(Yes, a bit of LOLCODE inspiration there too)

I’m sure this has been done by many before me, because it’s so simple. And that’s what I like about it. The implementation is simple beause the concept is simple. Simplicity beats complexity any day.

The Sasquatch: Fact Or Fiction?