Monday, March 28, 2011

Why Ruby has rand(x) instead of x.rand

When I was choosing a new language to work with after PHP, I was considering Python and Ruby. Both claim to be pure object-oriented languages, but some argue that Ruby is "more" OO because Python has things like abs(-3), which in Ruby is -3.abs (ie, it makes more sense if abs is a method of numeric objects).

However, recently I was faced with rand(1000). "Gosh! Wouldn't it be 1000.rand?! Why Ruby could be so 'not-OO'?"

After thinking for a while and read the rand documentation, it becames clear to me that the original purpose of rand is to give us a (pseudo) random float number between 0 and 1. And that isn't a numeric method; there's no sense in saying 693.rand to get a random number between 0 and 1. So it was implemented in module Kernel, like a procedural function accessible anywhere. Then, to increase the usability of rand, they decided to take an optional parameter to return a random number between 0 and it, if it is supplied. IMHO, that's why Ruby has rand(x) instead of x.rand.

Anyway, you can easily implement x.rand in Integer class. ;-)

No comments:

Post a Comment