は、デモ・コードを見て:インスタンス内のクラス変数にアクセスするにはどうすればよいですか?
class A
def method_a
puts "this is method_a"
end
end
class B < A
def self.hide_method name
if instance_methods.include? name
@hidden_mthod ||= {}
@hidden_mthod[name] = instance_method name
undef_method name
end
end
def self.invoke_hidden_methods
puts @hidden_mthod.inspect
end
def bound_method name
self.class.class_variable_get(:@hidden_mthod)[name].bind(self)
end
end
b = B.new
b.method_a
B.hide_method :method_a
B.invoke_hidden_methods
b.bound_method :method_a **#error**
b.method_a **#error**
私がやりたい事は、私はインスタンスメソッドとクラスで定義されて@hidden_methodにアクセスする方法をinstance.butに特別な方法を再バインドのですか?
更新日: ありがとう、ボリスストランドジェフ、ウル本当に素敵な男。もし上記のように、私は、コードをよりこのように簡略化されるべきだと思う:
def bound_method name
self.class.instance_variable_get(:@hidden_mthod)[name].bind(self)
end
これはインスタンス変数ではなく、クラスです。
def bound_method name
method_body = self.class.instance_variable_get(:@hidden_method)[name]
self.class.send :define_method, name, method_body
end
ボリス・ストランドジェフの答えです。それでも、最後のステートメントは実行できません。 – LeoShi