From: Jean-Hugues ROBERT Date: 2004-04-23T21:20:56+09:00 Subject: Re: Creating bang methods At 08:19 22/04/2004 +0900, you wrote: >Hi -- > >"Jon Hurst" writes: > > > On reflection, perhaps I have not been clear enough. I would like to create > > bang methods of some math functions (mostly abs), but I don't know how to > > modify the reciever in place because the value of self cannot be changed. > > It's not really important that I be able to write these bang methods, but I > > would very much like to understand how one would do it. > > > > Class Numeric > > def abs! > > ?? > > end > > end > >Not being able to assign to self actually isn't the issue (no method >can do that). I think you want this: > > x = -1 > x.abs! > >to result in x == 1, but that isn't how bang methods work; i.e., they >don't assign a new object to a variable, but rather they change an >object in place (and, if there are one or more variables referencing >that object, those variables don't "know" that this has happened). > > irb(main):002:0> x = [1,2] > => [1, 2] > irb(main):003:0> x.id > => 537881530 > irb(main):004:0> x.reverse! > => [2, 1] > irb(main):005:0> x.id > => 537881530 > >Nothing has happened to x in this example (no reassignment) but the >underlying array has been modified. > >The problem with abs! is that you can't modify a number in place, >because numbers are immediate values (even when referenced by >variables), and there's only one copy of each in existence. So if you >did this: > > -1.abs! > >then henceforth 1 + -1 would be 2, because you would have changed -1 >*itself* to 1 (not just assigned 1 to a variable that previously >referenced -1). The same would be true of this: > > x = -1 > x.abs! # x is the immediate value -1 > >This is also why there are no ++ and -- operators in Ruby. 1++ would >mean that the actual number 1 would henceforth mean 2. >David Well... something++ could get expanded into (something = something.++()) ? And ++something get expanded into (tmp = something, something = something.++(), tmp) Pure syntax sugar. Then you can: def ++() self + 1 end I think += does that already, doesn't it ? There are other reasons why there is no ++ in Ruby. Jean-Hugues