如何检查ruby中是否定义了私有方法

前端之家收集整理的这篇文章主要介绍了如何检查ruby中是否定义了私有方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我能找到的最接近的是 In Ruby,how do I check if method “foo=()” is defined?,但只有当方法是公共的时,它才有效,即使在类块内.

我想要的是:

  1. class Foo
  2. private
  3.  
  4. def bar
  5. "bar"
  6. end
  7.  
  8. magic_private_method_defined_test_method :bar #=> true
  9. end

我尝试过的:

  1. class Foo
  2. private
  3.  
  4. def bar
  5. "bar"
  6. end
  7.  
  8. respond_to? :bar #=> false
  9. #this actually calls respond_to on the class,and so respond_to :superclass gives true
  10. defined? :bar #=> nil
  11. instance_methods.include?(:bar) #=> false
  12. methods.include?(:bar) #=> false
  13. method_defined?(:bar) #=> false
  14. def bar
  15. "redefined!"
  16. end # redefining doesn't cause an error or anything
  17.  
  18. public
  19. def bar
  20. "redefined publicly!"
  21. end #causes no error,behaves no differently whether or not #bar had been defined prevIoUsly
  22. end

解决方法

另一种方法是使用:respond_to ?,例如
  1. self.respond_to?(:bar,true)

请注意,第二个参数在这里很重要 – 它表示:respond_to?应该寻找所有范围方法,包括私有方法.

猜你在找的Ruby相关文章