Hi --

On Sat, 25 Aug 2007, John Dearden wrote:

> I am trying to write a method that changes the value of two arguments.
> Stripped to the barest essentials, something like this:
>
> def munge(a)
>    a = a + 1
> end
>
> zot = 3
> print zot, "\n"  # this should (and does) print '3'
> munge(zot)
> print zot, "\n"  # this should print '4'.  We wouldn't be here now if it
> did!
>
> Now, if I try the amend method given by David A. Black, it works as
> expected.  But it's passing a string object, not an integer.
>
> Surely there is a way to give a method _something_ so that it can return
> values to the caller.  Of course, if I only ever had a single value to
> return, I could make it the return value, but that's just begging the
> question.

Since integers are immutable (luckily!), and local variables are
local, you can't change an integer object via a reference copied to a
method. If it helps, I can assure you that you would *not* want this
to happen. It would be very weird if my local variables bindings were
at the mercy of methods that I called.

What you're really looking for is an object container, and local
variables don't really work that way. For container semantics you
really need to use containers. You could do something like:

   def munge(a)
     [*a][0] += 1
   end

   z = 3
   y = *munge(z)

and so forth.


David

-- 
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)