From: Shannon Fang Date: 2002-11-28T06:54:37+09:00 Subject: Re: call-by-reference problem again Another problem about reference is that, if a is an object, let b=a, then b is a copy of the object or a pointer to a? I encountered the following problem a=b=c=Array.new d=e=f="" In my program, if I modify a, b and c will be affected, in another word, a, b, c point to the same Array. while I modify d, e and f are not affected, which means, strings are assigned by value... what will happen if I write d=e=f=String.new? Since everything in Ruby is object, I don't understand why String and Array are different... 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