【问题标题】:Making things available only inside Ruby blocks让东西只在 Ruby 块中可用
【发布时间】:2009-10-18 00:47:08
【问题描述】:

有没有办法让方法和函数只在块内可用?我正在尝试做的事情:

some_block do
    available_only_in_block
    is_this_here?
    okay_cool
end

但is_this_here?、okay_cool 等只能在该块内部访问,不能在其外部访问。有什么想法吗?

【问题讨论】:

  • 我不确定我理解你想要什么。是okay_cool 和公司变量还是方法?如果它们是变量,请在块中声明它们,它们将是块的本地变量。

标签: ruby dsl


【解决方案1】:

将带有您希望可用的方法的对象作为参数传递到块中。这是一种在 Ruby 中广泛使用的模式,例如在 IO.open 或 XML builder 中。

some_block do |thing|
    thing.available_only_in_block
    thing.is_this_here?
    thing.okay_cool
end

请注意,您可以使用instance_eval 或instance_exec 更接近您的要求,但这通常是一个坏主意,因为它可能会产生相当令人惊讶的后果。

class Foo
  def bar
    "Hello"
  end
end

def with_foo &block
  Foo.new.instance_exec &block
end

with_foo { bar }      #=> "Hello"
bar = 10
with_foo { bar }      #=> 10
with_foo { self.bar } #=> "Hello

如果你传入一个参数,你总是知道你将指的是什么:

def with_foo
  yield Foo.new
end

with_foo { |x| x.bar }      #=> "Hello"
bar = 10
x = 20
with_foo { |x| x.bar }      #=> "Hello"

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 2010-11-27
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2011-12-05
    • 2013-08-09
    相关资源
    最近更新 更多