From: dblack@... Date: 2007-06-05T22:16:33+09:00 Subject: Re: Writing method "change!" for String Hi -- On Tue, 5 Jun 2007, Harry Kakueki wrote: > On 6/5/07, Mike wrote: >> Hi, >> >> I'm trying to write simple method to change internal value of >> String class: >> >> class String >> def change! >> self="0" if self.downcase=="myvalue1" >> self="1" if self.downcase=="myvalue2" >> self >> end >> end >> >> test="myvalue1" >> test.change! >> p test >> >> It should just change value of string to what I want. But I get error: >> "Can't change the value of self". >> How do I proceed? >> >> Thanks. >> >> >> > Do not try to change self. > > Try this. > > class String > def change! > val="0" if self.downcase=="myvalue1" > val="1" if self.downcase=="myvalue2" > val > end > end > > test="myvalue1" > p test.change! > p test I think even the original idea probably wasn't a good !-candidate (since bang methods generally have non-bang equivalents, whereas methods with names that imply change or other "danger" [like replace] don't), and definitely if you're not modifying the string or doing anything else dangerous, the ! is not a good idea, since it's out of keeping with the convention. David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)