如何判断类中是否定义了某个方法?
class C1
unless method_defined? :hello # Certainly, it's not correct. I am asking to find something to do this work.
def_method(:hello) do
puts 'Hi Everyone'
end
end
end
那么,如何判断一个方法是否已定义呢?
class C1
unless method_defined? :hello # Certainly, it's not correct. I am asking to find something to do this work.
def_method(:hello) do
puts 'Hi Everyone'
end
end
end
So, how to judge whether a method has defined or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您发布的代码可以很好地检查该方法是否已定义。
Module#method_define?
正是正确的选择。 (还有变体Module#public_method_define?
< /a>,Module#protected_method_define?
和Module#private_method_define?
.) 问题在于您对def_method
的调用,该调用不存在。 (它被称为Module#define_method
)。这就像一个魅力:
但是,由于您已经提前知道名称并且不使用任何闭包,因此不需要使用
Module#define_method
,您只需使用def
关键字:或者我误解了你的问题并且你担心继承?在这种情况下,
Module#method_define?
不是正确的选择,因为它遍历整个继承链。在这种情况下,您必须使用Module#instance_methods
或其同类
Module#public_instance_methods 之一
,Module#protected_instance_methods
或
Module#private_instance_methods
,它接受一个可选参数,告诉他们是否包含超类/混合中的方法。 (请注意,文档是错误的:如果您不传递任何参数,它将包含所有继承的方法。)这是一个小测试套件,表明我的建议有效:
The code you posted works just fine for checking whether the method is defined or not.
Module#method_defined?
is exactly the right choice. (There's also the variantsModule#public_method_defined?
,Module#protected_method_defined?
andModule#private_method_defined?
.) The problem is with your call todef_method
, which doesn't exist. (It's calledModule#define_method
).This works like a charm:
However, since you already know the name in advance and don't use any closure, there is no need to use
Module#define_method
, you can just use thedef
keyword instead:Or have I misunderstood your question and you are worried about inheritance? In that case,
Module#method_defined?
is not the right choice, because it walks the entire inheritance chain. In that case, you will have to useModule#instance_methods
or one of its cousinsModule#public_instance_methods
,Module#protected_instance_methods
orModule#private_instance_methods
, which take an optional argument telling them whether to include methods from superclasses / mixins or not. (Note that the documentation is wrong: if you pass no arguments, it will include all the inherited methods.)Here's a little test suite that shows that my suggestion works:
查看 Ruby 对象类。它有一个
methods
函数来获取方法列表,并有一个respond_to?
来检查特定方法。所以你想要这样的代码:Look at the Ruby Object class. It has a
methods
function to get an list of methods and arespond_to?
to check for a specific method. So you want code like this:Object 类具有方法“methods”: docs
The Object class has the method "methods": docs