Ruby 对象中的实例变量在哪里?
调用Ruby 对象中的实例变量在哪里?,ruby,object,Ruby,Object,调用method\u missing时,为什么在Object中看不到@obj.instance\u变量 module Arena class Place def initialize obj @obj = obj method_missing_in_obj @obj.instance_variable_set(:@unit, '10') puts @obj.instance_variables yield @obj
method\u missing
时,为什么在Object
中看不到@obj.instance\u变量
module Arena
class Place
def initialize obj
@obj = obj
method_missing_in_obj
@obj.instance_variable_set(:@unit, '10')
puts @obj.instance_variables
yield @obj
end
def method_missing_in_obj
def @obj.method_missing method, *args, &blk
puts @obj.instance_variables
super
end
self
end
end
end
Arena::Place.new(Object.new) do |obj|
puts obj.instance_variable_get(:@unit)
puts obj.foo
end
$>ruby test\u me.rb
:
=> @unit
=> 10
=> in `method_missing': undefined method `foo' for #<Object:0x007fd89b1c96e0 @unit="10"> (NoMethodError)
=>@单位
=> 10
=>在'method_missing'中:为#未定义的方法'foo'(NoMethodError)
这是一个微妙的错误!问题是,当您定义@obj.method\u missing
时,您正在调用@obj.instance\u变量。请记住,这在@obj
的单例类中定义了一个方法,因此当您在方法定义中使用@obj
时,您需要@obj
的实例变量@obj
,它是nil
(并且nil
没有实例变量)
您所需要做的就是删除显式接收器,因为@obj
隐式地是在其singleton类中定义的方法的接收器
def method_missing_in_obj
def @obj.method_missing method, *args, &blk
puts instance_variables
super
end
self
end