William Djaja Tjokroaminata <billtj / y.glue.umd.edu> writes:

> Shannon Fang <xrfang / hotmail.com> 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