From: Michael Morin Date: 2008-08-21T13:16:53+09:00 Subject: Re: unintuitive language feature (exclamation functions) Nick Brown 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. > > 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. > > 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). > > So what do you think? Would warnings in the documentation on exclamation > functions be useful or pointless? This works. Doing it this way returns the actual string, not some string extended by undocumented modules that's actually an array in disguise or something like that. require 'cgi' cgi = CGI.new('html4') a = cgi.params['a'][0] a.sub!(/hi/, 'bye') puts a -- Michael Morin Guide to Ruby http://ruby.about.com/ Become an About.com Guide: beaguide.about.com About.com is part of the New York Times Company