Created
March 25, 2014 07:51
-
-
Save youcune/9756970 to your computer and use it in GitHub Desktop.
Rubyでクラス変数の使い方の例
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
#!/usr/bin/env ruby | |
class Parent | |
def self.puts_var | |
puts self.class_variable_get(:@@CLASS_VAR) | |
end | |
def puts_var | |
puts self.class.class_variable_get(:@@CLASS_VAR) | |
end | |
end | |
class Child1 < Parent | |
@@CLASS_VAR = 'Child1' | |
end | |
class Child2 < Parent | |
@@CLASS_VAR = 'Child2' | |
end | |
Child1.puts_var # => Child1 | |
Child1.new.puts_var # => Child1 | |
Child2.puts_var # => Child2 | |
Child2.new.puts_var # => Child2 |
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
#!/usr/bin/env ruby | |
class Parent | |
# 差分はここだけ。これがあると、子クラス同士の影響を受けてしまう | |
@@CLASS_VAR = 'Parent' | |
def self.puts_var | |
puts self.class_variable_get(:@@CLASS_VAR) | |
end | |
def puts_var | |
puts self.class.class_variable_get(:@@CLASS_VAR) | |
end | |
end | |
class Child1 < Parent | |
@@CLASS_VAR = 'Child1' | |
end | |
class Child2 < Parent | |
@@CLASS_VAR = 'Child2' | |
end | |
Child1.puts_var # => Child2 | |
Child1.new.puts_var # => Child2 | |
Child2.puts_var # => Child2 | |
Child2.new.puts_var # => Child2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment