From: David Alan Black Date: 2002-01-15T10:28:31+09:00 Subject: (non-)destructive methods (was: Re: a wishlist for ruby 2.0) Hello -- On Tue, 15 Jan 2002, Daniel Berger wrote: > >"David Alan Black" wrote in message > news:Pine.LNX.4.30.0201141607220.12386-100000@candle.superlink.net... > >I don't mind the separate methods, but if I did... :-) I wouldn't want > >the context to be the determinant. For one thing, you might want to > >return a mapped array: > > > def add_three(a) > > a.map {|e| e + 3} > > end > > > where you wouldn't want the receiver automatically modified. > > Hopefully, my above examples make it clear that, if you assign the result, > the receiver *won't* be modified. Here's some pseudo code: > > def add_three(a) > if want.lvalue > b = a.copy > b.map {|e| e + 3} > return b > else > a.map{|e| e + 3} > return a > end > end > > # Would modify receiver > array.add_three In my code (and yours :-) add_three isn't a method of Array, and it takes an argument. So "array.add_three" isn't the right call. > new_array = array.add_three.print Ditto. > # Would not modify receiver > new_array = array.add_three Ditto. Slightly crossed wires here: in my example, add_three was not a method of Array; it was a method whose argument is an array (well, a respondent to map). I was just using map to generate a new array. Your version is also a method whose argument is an array, but you haven't supplied the arguments to your method calls. A more complete version of my example would be: def add_three(some_array) some_array.map {|e| e + 3} end ary = [1,2,3] new_ary = add_three(ary) Here, if your rule is respected, ary will be modified, as a side-effect of having been the argument to add_three (because the code inside add_three does the non-lvalue map). > >> Can you explain what you mean by a special generic method? > > The other solution, to cut the gordian knot so to speak, would be to just > make the Ruby interpreter understand that an exclamation point at the tail > of any method name indicate that the receiver should be modified in place. > This would make our lives easier, but Matz's harder. Which brings me to my next question... :-) How exactly would this make our lives easier? I guess I'm not getting (or have not stumbled across) the cases where this is a problem. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav