Class and Object Relationship in Ruby07 Jul 2011 | Comments
I am about to finish Chapter 3 of Well Grounded Rubyist.
The book is excellent, I really enjoy reading it - in fact as far as I can remember this is the first technical book that I just can’t put down. I finally understood some of the Ruby concepts that I failed to grasp from the previous two Ruby books that I read. At least it helped me hacking adding features to dailymile ruby gem.
Let’s talk about Object Oriented Programming for second. In a way, all of Object Oriented languages are the same: you build this class, instantiate it, make the class extends other class etc2. Traditionally also (taking from Java perspective here) - Class is a blue print of objects.
I’m going to try an analogy here. Think of a factory producing a certain product, let’s say a helmet. The product designer designed the helmet and documented in the specification (ie: the blue print) - the factory/the machine will then produce helmet as the blue print dictates. And so every individual helmets should be similar to each other. And here my analogy fails - since individual objects can have their own states - so they are not exactly the same - but behaviorly the should be the same.
In Ruby, it’s different. Yes, Class does dictate objects’ behavior - but only initially. In Ruby, you can inject behaviors into object instances.
This is an example from the book:
[ruby] mag = Magazine.new def mag.wings puts "Look! I can fly!" end [/ruby]
Sidetracking a bit - example like above that I really like about this book - looks silly but drives the point home clearly.
Quoting from the book:
The inheritance tree - the upward cascade of class to superclass and super superclass - isn't the only determinant of an object's behavior.
I am yet to see how this might be useful in designing a solution. It looks powerful and dangerous.