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 |
Yeah, ruby class variables are shared by all subclasses. I wrote this for demonstration purposes.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I totally trolled this out of the stream.
Looks like this is a scope resolution problem with static properties. In php you can use
self::
to access the local member,parent::
to access the parent, and in the parent, when wanting to use the child's property you can usestatic::
which uses runtime scope resolution unlikeself::
andparent::
which are bound at compile time.Does ruby not have a way to represent that hierarchy?