Skip to content

Instantly share code, notes, and snippets.

@davidbalbert
Created July 13, 2012 19:17
Show Gist options
  • Save davidbalbert/3106790 to your computer and use it in GitHub Desktop.
Save davidbalbert/3106790 to your computer and use it in GitHub Desktop.
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
[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
@WanaByte
Copy link

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 use static:: which uses runtime scope resolution unlike self:: and parent:: which are bound at compile time.

Does ruby not have a way to represent that hierarchy?

@davidbalbert
Copy link
Author

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