LoginSignup
11
9

More than 5 years have passed since last update.

Rubyのクラス変数を継承関係にあるクラスに伝搬しないようにする方法

Last updated at Posted at 2014-07-30

あまりクラス変数使わないし、たまに直感に反する挙動してハマることあるのでメモ。


継承を利用している場合、クラス変数を普通に使うと親クラスやサブクラスに伝搬してしまいます。

class Base
  def self.foo=(value)
    @@foo = value
  end

  def self.foo
    @@foo
  end
end

class Sub1 < Base
  self.foo = 'sub1'
end

class Sub2 < Base
  self.foo = 'sub2'
end

puts Base.foo #=> "sub2"
puts Sub1.foo #=> "sub2"
puts Sub2.foo #=> "sub2"

全部"sub2"になっちゃったYO!

意図通りな挙動を実現するためにはこんな感じ。

class Base
  class << self
    def foo=(value)
      @foo = value
    end

    def foo
      @foo
    end
  end
end

class Sub1 < Base
  self.foo = 'sub1'
end

class Sub2 < Base
  self.foo = 'sub2'
end

puts Base.foo #=> nil
puts Sub1.foo #=> "sub1"
puts Sub2.foo #=> "sub2"

これで期待通りの挙動になりました。

11
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9