1

Any Ruby guru that explain this?

class Bar
  @@x = 10
  def self.test
    return @@x
  end
end

class Foo < Bar
  @@x = 20  
end


puts Bar.test  # 20 why not 10?
puts Foo.test  # 20 

When i run this from TextMate. I would expect that

puts Bar.test returns 10

and

puts Foo.test returns 20

But for some reason (that i would love to know) @@x in Foo updates Bar as-well, which is the super class. What is it i'm missing?

Roger
  • 7,535
  • 5
  • 41
  • 63

1 Answers1

2

This is to be expected. Class variables are shared within the hierarchy. See section in Wikipedia: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Variables_and_Constants#Class_Variables

Compare this to class instance variables, which are private to that class only.

class Bar
  @x = 10
  def self.test
    return @x
  end
end

class Foo < Bar
  @x = 20  
end


Bar.test # => 10
Foo.test # => 20
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • Thanks. 'An important note is that the class variable is shared by all the descendants of the class'. Its descendants parts that throws me off, u understand it works downward, but never expected it to be upwards as-well.. – Roger Aug 10 '12 at 21:23