From: Paul Brannan Date: 2002-04-11T22:49:53+09:00 Subject: Re: ruby-dev summary 16501-16750 (immutable?) On Thu, Apr 11, 2002 at 07:01:16PM +0900, Yukihiro Matsumoto wrote: > Unless you overload operator +=. I can overload operator+= and still get mutability: #include struct Foo { Foo(int x) : x_(x) { } int x_; }; int operator+=(int & lhs, Foo const & rhs) { lhs = lhs + rhs.x_; } main() { int x(1); Foo y(2); x += y; std::cout << x << std::endl; // 3 } The difference here is that in Ruby I can't implicitly get a reference to an immutable. I can, however, write a wrapper: # (I use succ! because I can't overload +=; note that it would not be # possible to write Integer#succ!) class IntegerHolder def initialize(integer) ; @integer = integer end def +(other) ; return type.new(@integer + other.to_i) end def to_s ; return @integer.to_s end def to_i ; return @integer.to_i end def succ! ; @integer += 1 end end def increment(x) x.succ! end x = IntegerHolder.new(42) increment(x) puts x # => 43 One solution to this problem would be to have macros for certain methods that implicitly creates an IntegerHolder whenever the method is passed an Integer. This might confuse extension writers, though. Paul