On Wed, Aug 20, 2008 at 3:45 PM, Nick Brown <ruby-forum.com / nick-brown.com> wrote: > I was surprised to discover that the code > > astring.sub!(/hi/, 'bye') > > behaves subtly differently from > > astring = astring.sub(/hi/, 'bye') > > Intuitively, to me, these should be identical. Perhaps the documentation > should make mention of this difference? A note about this unexpected > behavior would have saved me a lot of frustration, and would likely do > the same for many others new to Ruby. If the two were identical, why would we have both sub and sub! methods? The extra punctuation would be useless if it existed 'just for fun' > To be honest, I'm still trying to find out exactly why these do > different things. The difference does not manifest itself with trivial > cases in irb; rather it shows up when I'm getting a string from cgi, > modifying it, then inserting it into a database. When using sub!, the > database ends up containing the pre-sub'd value of astring, even though > astring appears to contain the modified version when printed with a > debug statement immediately preceding my database insert. The documentation for String#sub! is: "Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed. " > I'm willing to except the criticism that my intuition is perverse in > some way, but when I started writing in Ruby I was really hoping it > would be a language one could use without having to understand how the C > underneath it all worked (defeating part of the purpose of "high level" > languages). This has nothing to do with C. It has to do with interface design, and is meant to make things more intuitive, not less. Admittedly there is nothing inherently intuitive about some_method!, except that it might make you feel like you should pay more attention, like... Caution! Once learned, this convention can be very helpful. > So what do you think? Would warnings in the documentation on exclamation > functions be useful or pointless? Since exclamation points are conventional and not behaviorly enforced in any way by Ruby itself, all ! methods should come with their own documentation. It does not necessarily mean 'modify the receiver in place', so further explanation is usually needed. Just remember that when you see foo and foo!, the latter is the one that the developer of the library you are using has indicated to require more attention, or be more specialized. If you're still not convinced, I recommend checking out a post by David Black on this topic, as it clearly explains the value of the convention: http://dablog.rubypal.com/2007/8/15/bang-methods-or-danger-will-rubyist -greg -- Technical Blaag at: http://blog.majesticseacreature.com | Non-tech stuff at: http://metametta.blogspot.com