考虑一下:
class Foo
def secret
@some_ivar
end
end
foo_instance = Foo.new
foo_instance.in_foos_context do
@some_ivar = "bar"
end
foo_instance.secret
=> "bar"
除了看起来可疑之外,这可能吗?如果是,我该如何实现in_foos_context
方法?
答案 0 :(得分:5)
您可以使用instance_eval
class Foo
def secret
@some_ivar
end
def in_foos_context(&block)
instance_eval(&block)
end
end
foo_instance = Foo.new
foo_instance.in_foos_context do
@some_ivar = "bar"
end
foo_instance.secret # => "bar"
答案 1 :(得分:1)
怎么样:
foo_instance.instance_variable_set '@some_ivar', 'bar'
foo_instance.secret
=> "bar"
组合#instance_variables
,#instance_variable_get
和#instance_variable_set
就是为此而设的。
答案 2 :(得分:0)
你可以这样做:
class Foo
def secret
@some_ivar
end
def in_foos_context(arg,&block)
instance_exec(arg,&block)
end
end
foo_instance = Foo.new
foo_instance.in_foos_context("bar") do |v|
@some_ivar = v
end
foo_instance.secret
# => "bar"