From: "David A. Black" Date: 2009-11-01T02:03:58+09:00 Subject: Re: In-place parameter modification Hi -- On Sun, 1 Nov 2009, Jordi Bunster wrote: > On Oct 31, 2009, at 12:44 PM, Robert Gleeson wrote: > >> Yup, you can write your own mutating methods that mutate the >> receiver(like chomp!, gsub!, sub!, and so on), but you can't mutate any >> of the core classes because you cannot reassign self. > > Some core classes know how to replace themselves: > > class String > def clobber! > replace '' > end > end > > I wonder why Object (or BasicObject) doesn't know this trick. I don't think "replace" has any generalizable semantics. You can't replace 2 with 3, for example (fortunately :-) > I also wonder why "replace" isn't called "replace!" :) The !/non-! methods come in pairs. The ! one is the "dangerous" one -- that is, the one that probably has side-effects, special-case semantics, etc. A lot of the "danger" involves changing the receiver, but not all of it (e.g., exit!). Therefore, if it's just one method, not a pair, it simply has a name that says what it does, without a !. String#replace has to be destructive. Otherwise the name is absurd. (str.replace("abc") can be better written as just "abc", if all it's doing is creating a completely new string with the characters "abc".) There's no one-to-one correspondence, in either direction, between receiver-changing methods and the !. Array#pop and friends, the various replace and clear methods, Hash#update -- there are lots of them. Here's some further reading on the !-convention (and its lamentable near-disappearance): http://dablog.rubypal.com/2007/8/15/bang-methods-or-danger-will-rubyist David -- The Ruby training with D. Black, G. Brown, J.McAnally Compleat Jan 22-23, 2010, Tampa, FL Rubyist http://www.thecompleatrubyist.com David A. Black/Ruby Power and Light, LLC (http://www.rubypal.com)