ruby - 使事物仅在 Ruby block 内可用

标签 ruby dsl

有什么方法可以使方法和函数只能在 block 内使用吗?我正在尝试做的事情:

some_block do
    available_only_in_block
    is_this_here?
    okay_cool
end

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

最佳答案

将带有您希望可用的方法的对象作为参数传递到 block 中。这是 Ruby 中广泛使用的模式,例如 IO.openXML 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"

关于ruby - 使事物仅在 Ruby block 内可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1583624/

相关文章:

ruby - 在 Windows 上运行 ruby​​ gem

用于 CustomClass 和数字/字符串的 Groovy CompareTo

elasticsearch - DSL如何查询匹配类型不起作用?

parsing - 使用 DCG 在 EBNF 的 Prolog 中实现 DSL 的困难

java - 如何在 Spring Integration Java DSL 中处理 ExecutorChannel 的错误 channel

ruby-on-rails - Flash 消息的 CSS 样式

ruby - cp : cannot stat ‘path/file’ : No such file or directory

java - Spring DSL 编辑并保存在代码中 - 可能吗?

ruby-on-rails - ActiveRecord:在没有 Rails 的情况下使用 ActiveRecord 时如何在 AR 模型之间共享连接

ruby - ruby 中的减法不少于 1