考虑一下:
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
方法?
考虑一下:
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
方法?
你可以使用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"
关于什么:
foo_instance.instance_variable_set '@some_ivar', 'bar'
foo_instance.secret
=> "bar"
组合#instance_variables
,#instance_variable_get
和#instance_variable_set
是为此而生的。
您可以执行以下操作:
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"