Home

One strange feature of Ruby is one's ability to add to one of the languages built-in classes.

Since almost everything in Ruby is objects, even data-types such as integers are just plain instances of the "Fixnum"(inherits from "Integer") class. As such, they have class-methods;

-10.abs => 10

or

"hello".length => 5

abs is a class method of "Fixnum" and length is a class method of the "String" class.

Here's the strange part. I can extend any one of these classes myself. For instance, say I want to calculate any integers corresponding fibonacci-number. Instead of specifically writing a method for this, I can just add one to the Integer class, like this:

class Integer
   def fibonacci
      a,b=0,1
      self.times do
         a,b = b, a+b
      end
      return a
   end
end

voilá:

10.fibonacci => 55

 

I haven't stumbled upon any scenario where this might be useful yet though, and I do suspect this "feature" might be error-prone if working on larger projects.

Last Updated (Saturday, 23 January 2010 15:00)

 
Search