From: Chris White Date: 2011-09-16T06:23:43+09:00 Subject: Re: Some newbie questions > So the @-sign in Ruby is like self in Python? Can someone confirm who > knows Python? Not so much. Much like Python, Ruby classes deal with self as well. However in Ruby that's passed around behind the scenes, so you won't see it in method definitions. Take for example the following: -------------------------------------- >>> class Test: ...   myvar = "This is a variable" ...   def mymethod(self): ...     return self.myvar ... >>> inst = Test() >>> inst.mymethod() 'This is a variable' -------------------------------------- Here in this case, the instance of Test, `inst` is being passed in as "self" to mymethod. Now something to note is that here: ------------------------------------ myvar = "This is a variable" ------------------------------------ Has the same `self` as ------------------------------------ return self.myvar ------------------------------------ Now in Ruby, things are different. When defining classes, self inside the class definition can be referring to two different things. Take for example a copy of the above: ------------------------------------ irb(main):001:0> class Test irb(main):002:1>   @myvar = "This is a variable" irb(main):003:1>   def mymethod irb(main):004:2>      @myvar irb(main):005:2>   end irb(main):006:1> end => nil irb(main):007:0> inst = Test.new => # irb(main):008:0> inst.mymethod => nil irb(main):009:0> ------------------------------------ Noticed that mymethod returned nil. This is because `self` in the context of where @myvar is located is the CLASS ITSELF: ------------------------------------ irb(main):009:0> class Test irb(main):010:1>   p self irb(main):011:1>   @myvar = "This is a variable" irb(main):012:1>   def mymethod irb(main):013:2>     @myvar irb(main):014:2>   end irb(main):015:1> end Test => nil ----------------------------------- That is because class definitions in Ruby are expressions that evaluate to the last statement of the class definition. In this case method definitions return nil, so that's the resulting value. We could change this however: ----------------------------------- irb(main):018:0> class Test irb(main):019:1>   @myvar = "This is a variable" irb(main):020:1>   def mymethod irb(main):021:2>     @myvar irb(main):022:2>   end irb(main):023:1>   "return value" irb(main):024:1> end => "return value" ----------------------------------- Notice how in this case, a string value is the last statement, so that string becomes the result of the class definition. Now when we were calling mymethod from an instance, the instance itself is passed in to mymethod instead. This is a crucial difference between Ruby and Python in how classes are defined. If at any time you get confused as to how methods/variables are being accessed, check the value of self. Regards, Chris White http://www.twitter.com/cwgem