gpt4 book ai didi

ruby-on-rails - Ruby 从类中获取实例方法定义

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:52 25 4
gpt4 key购买 nike

我正在尝试从 Class 对象获取方法 :foo 的定义。

class Bar
def foo(required_name, optional="something")
puts "Hello args are #{required_name}, #{optional}"
end

def self.bar
puts "I am easy, since I am static"
end
end

无法创建类的实例,因为我需要方法定义来评估我是否应该创建对象(应用程序要求)。 Bar.class.???(:foo)

我可以用 Bar.class.method(:bar) 得到 bar 定义,但我当然需要 foo,谢谢!

更新:

使用 Ruby 1.8.7

最佳答案

您可以像这样在类上使用方法 instance_method :

Bar.instance_method(:foo)

这将返回 UnboundMethod 的一个实例。 (参见 http://ruby-doc.org/core-1.9.3/UnboundMethod.html)

关于ruby-on-rails - Ruby 从类中获取实例方法定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12056273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com