使事物仅在 Ruby 块内可用

发布于 2024-08-07 21:44:27 字数 230 浏览 2 评论 0原文

有什么方法可以使方法和函数只能在块内使用吗?我想要做什么:

some_block do
    available_only_in_block
    is_this_here?
    okay_cool
end

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

Is there any way to make methods and functions only available inside blocks? What I'm trying to do:

some_block do
    available_only_in_block
    is_this_here?
    okay_cool
end

But the is_this_here?, okay_cool, etc. only being accessible inside that block, not outside it. Got any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

层林尽染 2024-08-14 21:44:27

将具有您希望可用的方法的对象作为参数传递到块中。这是 Ruby 中广泛使用的模式,例如 IO .openXML 构建器

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

请注意,您可以使用 < 更接近您所要求的内容代码>instance_eval< code>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"

Pass an object with the methods that you want to be available into the block as an argument. This is a pattern that's widely used in Ruby, such as in IO.open or XML builder.

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

Note that you can get closer to what you asked for using instance_eval or instance_exec, but that's generally a bad idea as it can have fairly surprising consequences.

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

While if you pass an argument in, you always know what you'll be referring to:

def with_foo
  yield Foo.new
end

with_foo { |x| x.bar }      #=> "Hello"
bar = 10
x = 20
with_foo { |x| x.bar }      #=> "Hello"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文