 |
Ruby has 100% genuine objects, no kidding! |
January 12, 2007
I always wondered why Ruby does not implement the unary operator ++ like most other programming languages I've work with in the past.
Today it all makes sense.
In Ruby, everything is an object. I've known that for quite a while but sometimes it's really easy to forget. So repeat after me.. IN RUBY, EVERYTHING IS AN OBJECT.
Ok, now that we've got that settled.. :)
To explain further, integers are immutable. That means you can't do 1 = 2. 1 is 1 and will always be 1. You can't change it no matter what you try. And since everything in Ruby is an object, even the number 1 has a class:
> irb
>> x = 1
=> 1
>> x.class
=> Fixnum
>> 1.class
=> Fixnum
The class Fixnum does not implement a ++ method. Instead you use either the next or succ methods to increase an object of type Fixnum (or Bignum for that matter) to the next higher value.
> irb
>> x = 1
=> 1
>> x.succ
=> 2
>> x
=> 1
The binary operator + is actually a method of the Fixnum class:
> irb
>> x = 1
=> 1
>> x.+ 1
=> 2
>> x
=> 1
|