Shining Ruby: Extending Classes

I've been playing with Ruby a little and there's one feature in Ruby that I particularly like: the ability to extend existing classes. For example, for as long as I've been programming using objects I wanted to add a method to integers called "timesSayZef". So you could do this:

100.timesSayZef()

And it would print "Zef" a hundred times. However, Java doesn't allow you to do this, C# doesn't allow you to do this, even Python doesn't allow you to do this (at least I couldn't get it to do it). However, Ruby does with this code:

class Fixnum
   def timesSayZef
      times { puts "Zef" }
   end
end

In Ruby when you define a class that already exists (such as Fixnum, which represents a number, such as 100), it will merge the two definitions. So in this case I would add a timesSayZef method to the Fixnum class. When I now do this:

10.timesSayZef

it will print:

Zef
Zef
Zef
Zef
Zef
Zef
Zef
Zef
Zef
Zef

Cool huh?

Ruby also allows you to extend existing objects with additional methods. For example:

class BoringClass
   def saySomething
      puts 'Something'
   end
end
module ZefStuff
   def sayZefIsCool
      puts 'Zef is cool!'
   end
end
bc = BoringClass.new
bc.saySomething
bc.extend(ZefStuff)
bc.sayZefIsCool

What I do here is first define a class. Then define a module. Create an instance of the class and then extend that instance with all the methods in the module. This example will print:

Something
Zef is cool!