int the above code section when a call printMe method it behaves as
expected. However if I remove the '@' symbol making x as a local
variable it throws an undefined name error. which is also as expected.
But can anyone explain me in the previous case, what is the class for @x.
int the above code section when a call printMe method it behaves as
expected. However if I remove the '@' symbol making x as a local
variable it throws an undefined name error. which is also as expected.
But can anyone explain me in the previous case, what is the class for @x.
Please explain me in details
You can find the current object by calling 'self'. If you open irb:
int the above code section when a call printMe method it behaves as
expected. However if I remove the '@' symbol making x as a local
variable it throws an undefined name error. which is also as expected.
But can anyone explain me in the previous case, what is the class for @x.
This can be a bit tricky b/c the toplevel namespace doesn't behave like
this code would if it were defined within a `class...end`, which is more
typical.
In this case @x belongs to `main` which is a special object that also
proxy's certain calls to Object class.
In the more typical case:
class X @x = 'Hello World'
def printMe
puts @x
end
end
The @x in the class scope is not the same as the @x in the method (instance
scope). Rather:
class X @x = 'Hello World'
def self.printMe
puts @x #=> 'Hello World'
end
end
@x is visible at the class level (the `self.` makes this a class method
instead of an instance method).
···
On Friday, December 9, 2011 7:01:24 AM UTC-5, Manav Gupta wrote:
@x = 'Hello world'
def printMe
puts @x
end
int the above code section when a call printMe method it behaves as
expected. However if I remove the '@' symbol making x as a local
variable it throws an undefined name error. which is also as expected.
But can anyone explain me in the previous case, what is the class for @x.
x is a local variable whose scope is limited to printMe(), and is
undefined.
No, that's not quite right. x here is a method call, not a local
variable, because there has been no assignment to x earlier in the scope
(in this case the body of method 'printMe'). That is:
puts x
is interpreted as if you had written
puts self.x
or puts x()
However, if you had written instead:
def printMe
if false
x = 123
end
puts x
end
then x would indeed be a local variable, and its value is 'nil' (because
the assignment which occurs earlier in the scope is not actually
executed)