Skip to content

Instantly share code, notes, and snippets.

@koki-h
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save koki-h/b4cfb9e1d0c667774cfa to your computer and use it in GitHub Desktop.

Select an option

Save koki-h/b4cfb9e1d0c667774cfa to your computer and use it in GitHub Desktop.
クラス変数がすべてのサブクラスで共有されることを示すコード
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