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.

I’m Sheriff John Bunnell, most people don’t even think about law enforcement until they either do something wrong, or get wronged them self. But police know that fighting crime is a full time job. If something isn’t going down now, it will be soon and officers have to be ready. So get ready, what we’re going to show you tonight is the ruthlessness of criminals, the toughness of cops and the clash if both sides refuse to back down.