2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyでクラスインスタンス変数にインスタンスメソッドからアクセスする

Last updated at Posted at 2016-05-06

あるクラスのインスタンス間でデータを共有する必要がありました。
クラス変数はクラスを継承した動作などに癖があるみたいなので、クラスインスタンスを使いたいところです。

インスタンスメソッドからはクラスインスタンス変数に直接アクセスできないので、クラスメソッドを挟む必要がありました。
以下のようにすれば目的の動作が実現できました。

class C
	class << self
	  # proxy methods
		def class_instance_variable
			@class_instance_variable
		end
		def class_instance_variable=(other)
			@class_instance_variable = other
		end
	end
	@class_instance_variable = 12

	def get_class_instance_variable
		self.class.class_instance_variable
	end

	def set_class_instance_variable(other)
		self.class.class_instance_variable = other
	end
end

a = C.new
p a.get_class_instance_variable # => 12

b = C.new
p b.get_class_instance_variable # => 12

a.set_class_instance_variable(-44)
p a.get_class_instance_variable # => -44
p b.get_class_instance_variable # => -44

2016/05/07 追記

@QUANON さんから「アクセサリを使えばもっとシンプルに書けるよ!」とのご指摘を頂きました。ありがとうございます!

class C
	class << self
	  # proxy methods
		attr_accessor :class_instance_variable
	end
	@class_instance_variable = 12

	def get_class_instance_variable
		self.class.class_instance_variable
	end

	def set_class_instance_variable(other)
		self.class.class_instance_variable = other
	end
end

a = C.new
p a.get_class_instance_variable # => 12

b = C.new
p b.get_class_instance_variable # => 12

a.set_class_instance_variable(-44)
p a.get_class_instance_variable # => -44
p b.get_class_instance_variable # => -44
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?