Created
July 13, 2012 19:17
-
-
Save davidbalbert/3106790 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Polygon | |
@@sides = nil | |
def self.sides | |
@@sides | |
end | |
def self.count | |
@@count | |
end | |
@@count = 0 | |
def initialize | |
@@count += 1 | |
end | |
end | |
class Triangle < Polygon | |
@@sides = 3 | |
end | |
class Square < Polygon | |
@@sides = 4 | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[1] pry(main)> require './classvars' | |
=> true | |
# This makes sense | |
[2] pry(main)> Polygon.count | |
=> 0 | |
[3] pry(main)> p = Polygon.new | |
=> #<Polygon:0x007fb0a1ec3cc8> | |
[4] pry(main)> t = Triangle.new | |
=> #<Triangle:0x007fb0a1ab01b8> | |
[5] pry(main)> s = Square.new | |
=> #<Square:0x007fb0a3080290> | |
[6] pry(main)> Polygon.count | |
=> 3 | |
# This doesn't! | |
[10] pry(main)> Square.sides | |
=> 4 | |
[11] pry(main)> Triangle.sides | |
=> 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, ruby class variables are shared by all subclasses. I wrote this for demonstration purposes.