Passing script input as method args always global?

Gerald Vim wrote in post #1127177:

This is not what Perl does at all.

This conversation has gone on quite a bit. It started out like “I don’t
know why this happens this way” and there were some attempts at
explaining it, but now it’s a lot more like “I want it to work like
Perl” and a bunch of ruby-evangelistic responses.

If you want it to do what Perl does, use Perl. Perl does Perl better
than Ruby.

Perl retains the passed reference unless
modified. Not so in Ruby where y becomes
a new copy as soon as it is mutated.

You need to be really careful when using words like “reference” and
“copy” and “mutated” that you are using them in the context of the
language.

START OF SCRIPT:

our $SCOPE_0_VARIABLES = {};

x = 1;

my $x_object = new Fixnum(1);
$SCOPE_0_VARIABLES->{x} = $x_object;

def foo x

x = x + 1

end

our $SCOPE_foo_VARIABLES = {x=>undef}; # variables in scope
our $SCOPE_foo_FINAL_VALUE = undef; # return value

#y = foo x
$SCOPE_foo_VARIABLES->{x} = $SCOPE_0_VARIABLES->{x};
# copy outer-x to inner-x

IN SUBROUTINE:

x = x + 1

my $intermediate_value = $($SCOPE_foo_VARIABLES->{x}) + 1; # x + 1
$SCOPE_foo_VARIABLES->{x} = $intermediate_value; # x = …
$SCOPE_foo_FINAL_VALUE = $SCOPE_foo_VARIABLES->{x}; # return value

IN OUTER SCOPE:

$SCOPE_0_VARIABLES->{y} = $SCOPE_foo_FINAL_VALUE; # y = …

There is no x.

Apologies if my perl is bad, I can never remember when to use % or -> or
.

On Wed, Nov 13, 2013 at 7:13 AM, Xavier N. [email protected] wrote:

Ruby passes references to objects by value.

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 2:43 PM, gvim [email protected] wrote:

Perl retains the passed reference unless modified. Not so in Ruby where
y

becomes a new copy as soon as it is mutated.

Not really. When you call a method in Ruby, the parameter variables are
initialized with a copy of the values hold by the arguments. Right away,
it
doesn’t depend on anything being mutated.

The semantics are easy:

  1. Variables hold references to objects.

  2. When a method is invoked, the arguments are used to initialize the
    parameter variables.

That’s all the mental model you need to build in Ruby.

Xavier N. wrote in post #1127181:

Not true. Java is pass by value, the JLS is clear about this:

When the method or constructor is invoked (§15.12),
the values of the actual argument expressions initialize
newly created parameter variables, each of the declared
Type, before execution of the body of the method or
constructor.

Whoops, I got that mixed up then, sorry. The effect is that of a

 void f(SomeType *Klazz);

in C/C++.