Passing script input as method args always global?

That example illustrates what you could do if you **had** pass by reference
semantics. And Ruby does not have those semantics, it has pass by value
semantics, therefore it works as you are seeing.

···

On Wed, Nov 13, 2013 at 1:23 PM, gvim <gvimrc@gmail.com> wrote:

On 13/11/2013 12:13, Xavier Noria wrote:

     a = 1
     b = 2
     def swap(a, b)
       b, a = a, b
     end
     a == 2 # => true
     b == 1 # => true

That's the idea. Perl implements pass by reference, and Ruby pass by
value. Ruby passes references to objects by value.

Which is what I would expect, but why does x retain its original value in
this example:

x = 2

def f(y)
  y = y + 1
  return y
end

puts f(x) #=> 3
puts x #=> 2

In your example a and b are mutated but in mine x remains unchanged.

Quoting gvim (gvimrc@gmail.com):

In your example a and b are mutated but in mine x remains unchanged.

Because in your method:

def f(y)
  y = y + 1
  return y
end

you receive an object, but you return another one. The fact that it is
still called 'y' (within your local method) does not insure that it is
the same thing.

Thus, the original object is indeed unchanged.

This is because the implementators of the sum of the Numeric class
decided that it was appropriate to return a new object when performing
a sum.

If you go back to my previous example, and substitute the plus method
so that instead of

  def +(new_v)
    @v+=new_v
    self
  end

it reads

  def +(new_v)
    Tally::new(@v+new_v)
  end

(note that I changed the name of the local variable so that things may
be easier to understand), then you will still have

puts f(var) #=> 3
puts var #=> 2

Carlo

···

Subject: Re: Passing script input as method args always global?
  Date: mer 13 nov 13 12:23:22 +0000

--
  * Se la Strada e la sua Virtu' non fossero state messe da parte,
* K * Carlo E. Prelz - fluido@fluido.as che bisogno ci sarebbe
  * di parlare tanto di amore e di rettitudine? (Chuang-Tzu)

Thanks for spelling this out. I'd gotten pass-by-reference and
pass-reference-by-value mixed up in my head, probably because it's been
ages since I had to deal with pass-by-reference.

···

On Wed, Nov 13, 2013 at 7:13 AM, Xavier Noria <fxn@hashref.com> wrote:

Ruby passes references to objects by value.

I know they're different. It's just that my example was simplified to try to work out what's going on but your use of a class with 3 different variable types doesn't clarify anything.

gvim

···

On 13/11/2013 12:20, Carlo E. Prelz wrote:

No! :v, v and @v are THREE DIFFERENT THINGS altogether.

:v is a symbol that, where it is used, references the name of an
instance variable

@v is the instance variable (local to the class instance, and thus
maintaining its value for the life of the instance)

v is a local variable whose scope is limited to each of the two
methods where it is used.

Carlo