Background on why Ruby doesn't support ++

A

Adam Lauper

Hi All,

I'm a big Ruby fan and I'm not trying to complain.

I'm just curious as to why Ruby doesn't support the ++ or -- operators.
Is there some syntactical ambiguity that's associated with it or
something.

Anyone know the history on this deliberate omission?

Thanks!

Adam
 
R

Robert Klemme

2009/8/13 Shajith Chacko said:

Basically it is a consequence of the decision to make integers
immutable which makes assignment necessary for a variable which is
incremented. I guess Matz wanted to make this explicit, hence "+="
Co.

Otherwise you need a counter class, e.g.

Counter = Struct.new :value do
def initialize(x = 0)
self.value = x
end

def plusplus
self.value += 1
end

alias incr plusplus

def minusminus
self.value += 1
end

alias decr minusminus
end

:)

Kind regards

robert
 
R

Robert Dober

2009/8/13 Shajith Chacko said:
Basically it is a consequence of the decision to make integers
immutable which makes assignment necessary for a variable which is
incremented.
Makes sense, though strictly speaking x++ could be syntactic sugar for
x+=3D1 or x =3Dx +1
but this would probably be very confusing for many folks for the very
reason you gave.
Cheers
Robert
--=20
module Kernel
alias_method :=EB, :lambda
end
 
M

Mark Thomas

Don't forget there's already

x.next

although there is not the orthogonal x.prev, which seems like the
Principle of Most Surprise in effect :). One way to rectify that is
to open up Integer yourself:

class Integer
def prev
self - 1
end
end
 
R

Robert Klemme

2009/8/13 Mark Thomas said:
Don't forget there's already

x.next

although there is not the orthogonal x.prev, which seems like the
Principle of Most Surprise in effect :). One way to rectify that is
to open up Integer yourself:

class Integer
=A0def prev
=A0 =A0self - 1
=A0end
end

There is also #succ and #pred. But this is not the point: all of them
work by returning _a different object_. You can easily verify by
looking at the result's #object_id. Operators ++ and -- in C++ on the
other hand change the object (int, long etc.) itself. The difference
is whether you will have aliasing or not.

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top