Created
November 13, 2011 15:44
-
-
Save zxcvbnm4709/1362236 to your computer and use it in GitHub Desktop.
一般來說,class static variable的accessor怎麼寫
This file contains 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 static variable是@@a這種 | |
# 我會這麼寫(至於多數人怎麼寫我就不清楚了...sorry = =") | |
class A | |
@@class_var = 'I am A' | |
def self.class_var | |
@@class_var | |
end | |
end | |
# 但是Ruby的設計,class static variable會被繼承 | |
# 所以會出現這樣的狀況 | |
class B < A | |
@@class_var = 'I am B' | |
end | |
p B.class_var # => "I am B" | |
p A.class_var # => "I am B" | |
# 因此,如果這不是你期望的行為 | |
# 那用常數或者singleton會比較好 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment