David Masover wrote:
John Pritchard-williams wrote:
> I did check my Ruby books by the way, but they just "unlike C there is
> no ++ operator in Ruby...." 
In ruby, operators are methods and they operate on objects, not on
variables.
I see no reason there couldn't be a ++ operator that behaves the same
way:
foo ++
# becomes
foo += 1
# or, probably better:
foo = foo.succ
You can define foo=, and you can define +, but you can't define +=.
Why not add a ++ that works the same way += does?
The answer is much simpler than people are turning it into: hopefully
this will explain the problem beyond argument (whether it's a sound
decision is another, much hairier topic).
Certain objects, like Fixnums, nil, and Symbols have a fixed object_id.
One can demonstrate this in irb quite simply:
irb(main):001:0> 1.object_id
=> 3
irb(main):002:0> 1.object_id
=> 3
irb(main):003:0> "foo".object_id
=> 69836108895520
irb(main):004:0> "foo".object_id
=> 69836108877060
irb(main):005:0> :bar.object_id
=> 332028
irb(main):006:0> :bar.object_id
=> 332028
irb(main):007:0> nil.object_id
=> 4
irb(main):008:0> nil.object_id
=> 4
irb(main):012:0> 1.succ.object_id
=> 5
irb(main):013:0> 2.object_id
=> 5
1.succ actually returns the object for Fixnum '2', which is a different
object id, but is still immutable. Notice how out of all of those calls,
the only similar object with different object id's is the string. Of all
of these, String objects are the only ones that are mutable (via
String#replace and whatnot).
1++ would have to operate (essentially) like 1.succ!, which would modify
the object itself. However, because of Fixnum's implementation, 1++
would create a situation that would be hard to reconcile: does it change
the object to the Fixnum 2 (and preserve the object id for 1,
effectively rendering 1 == 2), does it create a new object that equates
to 2 (making 2 == 2 increase in complexity) or the current Fixnum
somehow needs to be encapsulated so that each Fixnum creation would be
mutable at some point.
Logically the last 2 situations are possible but in practice they would
be extremely slow, especially if those classes were malleable by ruby
programs.
The reality is that Ruby *could* support ++ for mutable objects (as
described elsewhere in this thread) for other objects (Float, for
example, creates mutable objects), but I personally believe that would
take confusion to a whole new level when it didn't work on Fixnums.
HTH,
-Erik
ยทยทยท
On Thursday 28 August 2008 16:25:59 Joel VanderWerf wrote:
--
Posted via http://www.ruby-forum.com/\.