Last active
August 29, 2015 14:27
-
-
Save koki-h/b4cfb9e1d0c667774cfa 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 A | |
| def set_class_variable | |
| @@a = class_variable #サブクラスで定義したメソッドを呼び出すことによってクラス変数の値をセットする | |
| end | |
| end | |
| class B < A | |
| def class_variable | |
| "class B" | |
| end | |
| def print_class_variable | |
| puts @@a | |
| end | |
| end | |
| class C < A | |
| def class_variable | |
| "class C" | |
| end | |
| def print_class_variable | |
| puts @@a | |
| end | |
| end | |
| b = B.new | |
| b.set_class_variable | |
| b.print_class_variable #=> "Class B" | |
| c = C.new | |
| c.set_class_variable | |
| c.print_class_variable #=> "Class C" | |
| b.print_class_variable #=> "Class C" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment