From: Intransition Date: 2011-12-13T02:26:14+09:00 Subject: Re: CONCEPT OF INSTANCE VARIABLE IN RUBY ------=_Part_2439_16223101.1323710771785 Content-Type: multipart/alternative; boundary="----=_Part_2440_31900472.1323710771786" ------=_Part_2440_31900472.1323710771786 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit 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. > > Please explain me in details > 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). ------=_Part_2440_31900472.1323710771786 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable
On Friday, December 9, 2011 7:01:24 AM UTC-5, Manav Gupta wrote:@x =3D 'Hello world'

d= ef printMe
   puts @x
end

int the above code section = when a call printMe method it behaves as
expected. However if I remove t= he '@' symbol making x as a local
variable it throws an undefined name e= rror. which is also as expected.
But can anyone explain me in the previo= us case, what is the class for
@x.

Please explain me in details


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...en= d`, which is more typical.

In this case @x belongs to `main` w= hich is a special object that also proxy's certain calls to Object class.
In the more typical case:

  class X
   = @x =3D 'Hello World'

    def printMe
  =     puts @x
    end
  end

T= he @x in the class scope is not the same as the @x in the method (instance = scope). Rather:

  class X
    @x =3D 'Hello World'

    def self.printMe
      puts @x   #=3D> 'Hello World'    end
  end

@x is visible at the class level (the `self.` makes this a class method= instead of an instance method).



------=_Part_2440_31900472.1323710771786-- ------=_Part_2439_16223101.1323710771785--