接受读取/分配实例变量的块

时间:2013-10-31 17:23:28

标签: ruby

考虑一下:

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方法?

3 个答案:

答案 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"