使事物仅在 Ruby 块内可用
有什么方法可以使方法和函数只能在块内使用吗?我想要做什么:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将具有您希望可用的方法的对象作为参数传递到块中。这是 Ruby 中广泛使用的模式,例如
IO .open
或 XML 构建器。请注意,您可以使用 < 更接近您所要求的内容代码>instance_eval或< code>instance_exec,但这通常是一个坏主意,因为它可能会产生相当令人惊讶的后果。
如果你传入一个参数,你总是知道你要指的是什么:
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.Note that you can get closer to what you asked for using
instance_eval
orinstance_exec
, but that's generally a bad idea as it can have fairly surprising consequences.While if you pass an argument in, you always know what you'll be referring to: