0

Code is worth a thousand words: why this code acts as it does?

class MyClass 
  @variable = 0

  class << self
    attr_accessor :variable 
  end

  puts variable # => 0, as expected
  variable = 1
  puts variable # => 1, as expected
  puts self.variable # added after @Arup's comments => 0
end

puts MyClass.variable # => 0, as really not expected!
MyClass.variable = 2
puts MyClass.variable # => 2, as expected

For the record, I have read all I could find on metaclasses and 'class is an object' theory, but this still makes no sense to me.

Which variable has been set by variable = 1 from inside the class, and which has been set by MyClass.variable = 2? How come that accessory is accessible from both inside the class definition and from outside, but it does a different thing?

Or just very simply: what is going on here?

zmilojko
  • 2,125
  • 17
  • 27
  • there are more - http://stackoverflow.com/questions/4699687/when-to-use-self-foo-instead-of-foo-in-ruby-methods and http://stackoverflow.com/a/44779/2767755 – Arup Rakshit Jun 01 '14 at 07:23
  • Why re opening vote is.. It is completely a dup question. I marked 3 answers. – Arup Rakshit Jun 01 '14 at 07:26
  • @ArupRakshit - the questions you are putting are not the same as mine, or even close. I am not asking about class level variables, I am asking about the `attr_accessor` in a metaclass. None, of the answers you are pointing to, including yours, explains what that accessor does. I am trying to get deeper into the matter of the metaclasses, not to be explained the `self` keyword. – zmilojko Jun 01 '14 at 07:26
  • Just take your breath and think about the same, that you are really didn't understand how the *setter* method works.. Those answers clearly is telling the same. – Arup Rakshit Jun 01 '14 at 07:28
  • `puts MyClass.variable # => 0, as really not expected!` --- this is because `variable = 1` is a local variable assignment, not your class level *setter* call. If you want to do this `self.variable = 1`.. This is what all answers are saying.. – Arup Rakshit Jun 01 '14 at 07:30
  • None of the answer is saying, what `self` does.. But is telling why *self* is needed in the *setter* call. – Arup Rakshit Jun 01 '14 at 07:31
  • @ArupRakshit - I am glad to admit you are right, and I was wrong (and that I got an answer 6 minutes after posting)! Never thought about this being local variable assignment - and thus could not find other answers. This also shows if I add `puts self.variable' at the end of class definition. – zmilojko Jun 01 '14 at 07:40
  • Good to hear.. BTW you got your answer within 3 mins.. not 6 mins.. Lollz – Arup Rakshit Jun 01 '14 at 07:53

0 Answers0