Hi,

From: "Shannon Fang" <xrfang / hotmail.com>
>
> Hi there,
> 
> I encountered the call-by-reference problem, which was discussed before
> in this group. Please have a look at the following code:

I'm confident the gurus can give more precision in their replies,
but here's my thought(s)...

> def test!(str)
>   str=str.upcase
> end

def test!(str)
  str.upcase!
end

> str="hello"
> print str,"\n"
> test!(str)
> print str,"\n"
> 
> The str is not turned into upcase. This seems clear since that "Ruby
> only pass by value". According to a post in this group, I tried change
> the parameter into an array, and it worked.
> 
> 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)?

Some of the Ruby built-ins, such as String, do provide ways to
swap-out their contents in-place.  For instance, String#[]=

irb> def test!(str); str[0..-1] = "some other str"; end
nil
irb> x = "xyzzy"
"xyzzy"
irb> x.id
22441516
irb> test!(x)
"some other str"
irb> x
"some other str"
irb> x.id
22441516

Here you can tell the contents of 'x' (the String object instance
referred to by 'x') were changed to a completely different string-text,
yet 'x' still refers to the original, same instance it has all
along...

However, as some recent discussions have pointed out, not all Ruby
objects are mutable... So there is no way I know of to implement
a Ruby method like test!() above for Fixnum, or Bignum, .....

But certainly in your own Ruby classes, it's up to you how many
test!-like methods you want to create.  (Since you have access to
the internals of your own object, in terms of its instance 
variables... [Modulo inheritance and the discussion of "private
instance variables" <grin>])

Anyway I believe the short answer is, essentialy: You can implement
self-changing* methods in your own Ruby classes, and some of the
built-ins provide ways to change their contents out as well...

Hope this helps,

Bill


(*) Not talking about assignment to "self", which isn't allowed...