From: gwtmp01@... Date: 2006-06-03T08:24:58+09:00 Subject: Re: Adding an Increment Operator? On Jun 2, 2006, at 6:02 PM, Dave Howell wrote: > > Although I will admit to being rather surprised that the answer to > the question > How do I do this? > whatever = 1 > whatever.increment > p whatever > => 2 > is apparently "You Can't." If you are surprised by this then you haven't fully absorbed Ruby's object model and/or assignment semantics. I know that assignments such as 'whatever = 1' are often described as copying the value 1 into the variable 'whatever' but I find that language highly misleading for Ruby. Not everyone thinks about it the way I do but read on if you are curious. Variables in Ruby are not containers for objects (or for values). If they can be said to 'hold' anything, then they hold references to objects (not the object itself). Similarly, integer literals do not represent values or objects but instead are labels bound (permanently) to particular references to instances of Fixnum (I'm ignoring BigNums). 4 is a constant reference to the Fixnum instance that behaves like the number 4. There is exactly one Fixnum instance that behaves that way. There are many ways to identify that object (4, 0b100, 0x4, 0x04) but all those labels are references to the same Fixnum instance. Assignment in Ruby is just the re-binding of a label from one object reference to another object reference. a = b causes 'a' to be bound to the same object reference that is associated with 'b'. a = 5 causes 'a' to be associated with the same object reference that is associated with 5, i.e. the reference (there can be only one) to the Fixnum object that behaves like the integer 5. If you want an expression like: a.increment to cause 'a' to be associated with the Fixnum instance 6 then you are talking about rebinding the variable 'a' so that it no longer is bound to the reference to the Fixnum 5. But the only way to rebind a variable is via assignment, so you are back to something like a = a + 1 or a = a.succ Internally Ruby doesn't actually allocate memory for instances of Fixnum. The internal representation of object references is structured so that Ruby can fake the existence of Fixnum instances (and other objects such as nil, true, and false). Ruby manipulates the references, the objects themselves are never explicitly realized.