A
Andreas Warberg
I am new to Ruby but have a strong java background.
So far I have been enjoying Ruby a great deal.
But I have been wondering about why the scope of variables works as it
does. It seems that very often, I need to prefix my variables with
either @ or $ in order to access them in method calls.
I did some searching for an explanation but did not find any.
In java variables can be defined and used like this:
Object x = myX;
public void printx(){
System.out.println(x);
}
x is available when the method is called. This is not the case with
Ruby:
x = myX
def printx
puts x
end
Running the code will produce an error: "NameError: undefined local
variable or method `x' for main:Object".
In order to reveal x to the method one must, for instance, declare it
global by prefixing the $. This requires more typing (which, in many
other respects, ruby tries to avoid).
How come the scope works in this way? I expected the visibility of
variables to flow down into the code tree (but not up, of course).
Thank you.
Regards, Andreas
So far I have been enjoying Ruby a great deal.
But I have been wondering about why the scope of variables works as it
does. It seems that very often, I need to prefix my variables with
either @ or $ in order to access them in method calls.
I did some searching for an explanation but did not find any.
In java variables can be defined and used like this:
Object x = myX;
public void printx(){
System.out.println(x);
}
x is available when the method is called. This is not the case with
Ruby:
x = myX
def printx
puts x
end
Running the code will produce an error: "NameError: undefined local
variable or method `x' for main:Object".
In order to reveal x to the method one must, for instance, declare it
global by prefixing the $. This requires more typing (which, in many
other respects, ruby tries to avoid).
How come the scope works in this way? I expected the visibility of
variables to flow down into the code tree (but not up, of course).
Thank you.
Regards, Andreas