Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
question about class variables and instance variables
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Jeremy Henty, post: 4503581"] Is this really the whole story? Because until now I always thought I didn't understand class variables but if this is so then now I do. Wheeeee! But there's at least one gotcha; a class variable shadows any class variable of the same name that you subsequently create in an ancestor class: $ irb irb(main):001:0> class A ; end ; class B < A ; end => nil irb(main):002:0> class B ; @@x = 1 ; end ; class A ; @@x = 0 ; end => 0 irb(main):003:0> class A ; puts @@x ; end ; class B ; puts @@x ; end 0 1 => nil irb(main):004:0> exit .... but if you create the class variable in the ancestor class first then the descendant class inherits it instead of creating a new one: $ irb irb(main):001:0> class A ; end ; class B < A ; end => nil irb(main):002:0> class A ; @@x = 0 ; end ; class B ; @@x = 1 ; end => 1 irb(main):003:0> class A ; puts @@x ; end ; class B ; puts @@x ; end 1 1 => nil irb(main):004:0> exit Any other subtleties? Cheers, Jeremy Henty [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
question about class variables and instance variables
Top