From: dblack@... Date: 2006-02-24T22:22:37+09:00 Subject: Re: Everything's an object, right? Hi -- On Fri, 24 Feb 2006, Huw Collingbourne wrote: > To the best of my knowledge everything (apart from integers) is passed by > reference. Have a look at Hal's post: it's more a question of passing by value, where the values happen to be references. For example: a = "hi" meth(a) you're actually passing the value of a -- which is a reference to the string that was assigned to a. If you use a literal construct as the argument: meth("hi") then it will be wrapped in a reference for the occasion. > However, 99% of the time this doesn't matter. In 'pure OOP' > programming, 'messages' are sent to 'methods' and they respond with new > data. If you only ever use return values you won't see inconsistent > behaviour and you won't break encapsulation (which, in effect, using ByRef > arguments to obtain new values does). > > To clarify. There are a few string methods which alter the original string > object. This is also the case if you index into a string to change a char. > > However, when you evaluate an expression, this yields a new object so that > in the following: > > x = x + 1 > > The expression on the right yields a value which is assigned to a new > object, x, on the left. In other words, the x on the right is a different > object from the x on the left. Since methods which alter data usually do so > in the process of evaluation and assignment, most of the time any object > (such as x) which "goes in" is assigned to a new object (with the same name) > by the time the method ends. This explains why many people believe that > arguments are sent 'by value' - because, in most cases, the value of any > argument that goes into a method is not changed. Rather, a new object is > created during the process of evaluation and assignment. > > If this is confusing, just stick to the 'pure OOP' way of doing things and > always use return values; never try to use the values of ingoing arguments > as 'ByRef' parameters. Life is much simpler that way ;-) Except that it takes you right back to the original problem -- namely, not understanding why the "values" you're manipulating are actually behaving like references :-) I'd discourage splitting the matter into the simple part and the confusing part. It's all reasonably simple, and certainly internally consistent -- and it's good to know what's actually happening, partly to avoid (or at least explain) unexpected errors, and partly to have as large a technique kit as possible should this or that need arise. David -- David A. Black (dblack@wobblini.net) Ruby Power and Light (http://www.rubypowerandlight.com) "Ruby for Rails" chapters now available from Manning Early Access Program! http://www.manning.com/books/black