From: Shannon Fang Date: 2002-11-28T06:51:27+09:00 Subject: Re: call-by-reference problem again In my class, I read some string from a text file, and store it in a local variable, then I defined a private method passing it the local variable, do some converstion, before it return, I tried to clear the string to "". It seems I can't do it. A solution I am now thinking is that I do not use a local variable, instead, use a instant variable... What do you think? Shannon On Thu, 28 Nov 2002 06:45:26 +0900 Dave Thomas wrote: > William Djaja Tjokroaminata writes: > > > Shannon Fang wrote: > > > The problem here is, we have seen some Ruby methods, like String.chomp! > > > and many that end with a !, they can modify parameters in place, how is > > > it done?? Is it possible to do this in programming, or is it only > > > available in standard libraries, which may be implemented outside of > > > ruby (eg. in C)? > > > > Hi, > > > > In general, for the Ruby built-in classes such as String, the methods are > > indeed implemented in C. For your own classes, probably it suffices to > > say that you cannot modify 'self' (such as 'self = something') in Ruby, > > but it is possible do that through the Ruby C API's. > > That's not really the point. A ! method modifies the state of an > object, not its value of 'self'. For example > > class Counter > attr_reader :count > > def initialize(value=0) > @count = value > end > > def succ > Counter.new(@count.succ) > end > > def succ! > @count += 1 > self > end > end > > > a = Counter.new > p a.count #=> 0 > b = a > c = a.succ > p b.count #=> 0 > p c.count #=> 1 > c = a.succ! > p b.count #=> 1 > p c.count #=> 1 > > > It's the same for Strings. Mutators change the state of the object: > the object reference stays the same. > > > > Dave