如何使用当前范围 (Ruby) 中的变量向对象实例添加方法?
这很难解释为一个问题,但这里有一个代码片段:
n = "Bob"
class A
end
def A.greet
puts "Hello #{n}"
end
A.greet
这段代码不起作用,因为 n 仅在调用时在 A.greet 内部求值,而不是在我添加方法时求值。
有没有办法将局部变量的值传递到 A.greet 中?
如果 n 是一个函数呢?
This is hard to explain as a question but here is a code fragment:
n = "Bob"
class A
end
def A.greet
puts "Hello #{n}"
end
A.greet
This piece of code does not work because n is only evaluated inside A.greet when it is called, rather than when I add the method.
Is there a way to pass the value of a local variable into A.greet?
What about if n was a function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用元编程,特别是
define_singleton_method
方法。这允许您使用块来定义方法并捕获当前变量。Use metaprogramming, specifically the
define_singleton_method
method. This allows you to use a block to define the method and so captures the current variables.您可以使用全局 ($n = "Bob")...
You can use a global ($n = "Bob")...
虽然我更喜欢 Nemo157 的方式,但你也可以这样做:
Although I prefer Nemo157's way you can also do this: