如何使用当前范围 (Ruby) 中的变量向对象实例添加方法?

发布于 2024-12-07 11:56:58 字数 233 浏览 2 评论 0原文

这很难解释为一个问题,但这里有一个代码片段:

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 技术交流群。

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

发布评论

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

评论(3

牵你手 2024-12-14 11:56:58

使用元编程,特别是 define_singleton_method 方法。这允许您使用块来定义方法并捕获当前变量。

n = "Bob"

class A
end

A.define_singleton_method(:greet) do
  puts "Hello #{n}"
end

A.greet

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"

class A
end

A.define_singleton_method(:greet) do
  puts "Hello #{n}"
end

A.greet
写下不归期 2024-12-14 11:56:58

您可以使用全局 ($n = "Bob")...

You can use a global ($n = "Bob")...

兔小萌 2024-12-14 11:56:58

虽然我更喜欢 Nemo157 的方式,但你也可以这样做:

n = "Bob"

class A
end

#Class.instance_eval "method"
A.instance_eval "def greet; puts 'Hello #{n}' end"

#eval Class.method
eval "def A.greet2; puts 'Hi #{n}' end"

A.greet
A.greet2

Although I prefer Nemo157's way you can also do this:

n = "Bob"

class A
end

#Class.instance_eval "method"
A.instance_eval "def greet; puts 'Hello #{n}' end"

#eval Class.method
eval "def A.greet2; puts 'Hi #{n}' end"

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