I am beginning to understand this:
If you assign to the variable within the function the original is
NOT
modified.
if you modify the variable within the function then the original
is modified.
That’s basically it.
v=99
def f1(n); n=n*n ; end
f1(v)
it will not work.
It will, as David said, but in your case, “v” is not changed (which
is what I think you were wondering about), where “n” is.
Yes , my last post was a bit confusing. Maybe , functions like my examples
are not the Ruby Way of coding.
After reading half a dozen of Perl books , I decided I was never going to
master OO perl ( and perlXS!) and took up Python.It is much easier than perl
but all those ‘sort() is a method: len() is a function’ type of rules bothered me.
That is how I came to Ruby.It is wonderful!.
However , I am still puzzled by the rules about function parameters.
Perl and Python both permit you to alter the original variable, or
work on copies of the variables inside function( as required by the
program logic).In Ruby, outside a function an assignments and modification
act the way you expect it to.Why should they behave differently inside a
function?
I am not a computer scientist; I presume there must some sound logic behind
this rule.
v.nainar
···
On Mon, Dec 08, 2003 at 04:03:39AM +0900, Michael Campbell wrote:
David A. Black wrote:
On Mon, 8 Dec 2003, nainar wrote:
I am beginning to understand this:
If you assign to the variable within the function the original is
NOT
modified.
if you modify the variable within the function then the original
is modified.
That’s basically it.
v=99
def f1(n); n=n*n ; end
f1(v)
it will not work.
It will, as David said, but in your case, “v” is not changed (which
is what I think you were wondering about), where “n” is.
However , I am still puzzled by the rules about function parameters.
Perl and Python both permit you to alter the original variable, or
work on copies of the variables inside function( as required by the
program logic).In Ruby, outside a function an assignments and modification
act the way you expect it to.Why should they behave differently inside a
function?
They don’t; it’s exactly the same. The best way to think of it is
that when you call a method with arguments, what takes place is
assignment:
def meth(x,y)
puts x + y
end
meth(3,4)
what happens is:
···
On Mon, 8 Dec 2003, nainar wrote:
x = 3
y = 4
s = “hi”
t = " there"
meth(s,t)
x = s
y = t
In that second case, the one with variables, once the implicit
assignment happens, x and y behave exactly like s and t. There’s no
special case, no special behavior.
def meth2(x,y)
x << y
end
s = “hi”
t = " there"
meth2(s,t)
puts s # “hi there”