我能找到的最接近的是在 Ruby 中,如何检查方法“foo=()”是否已定义? https://stackoverflow.com/questions/2348521/in-ruby-how-do-i-check-if-method-foo-is-defined,但仅当该方法是公共的时才有效,即使在类块内也是如此。
我想要的是:
class Foo
private
def bar
"bar"
end
magic_private_method_defined_test_method :bar #=> true
end
我尝试过的:
class Foo
private
def bar
"bar"
end
respond_to? :bar #=> false
#this actually calls respond_to on the class, and so respond_to :superclass gives true
defined? :bar #=> nil
instance_methods.include?(:bar) #=> false
methods.include?(:bar) #=> false
method_defined?(:bar) #=> false
def bar
"redefined!"
end # redefining doesn't cause an error or anything
public
def bar
"redefined publicly!"
end #causes no error, behaves no differently whether or not #bar had been defined previously
end
另一种方法是使用:respond_to? https://apidock.com/ruby/Object/respond_to%3F
, e.g.
self.respond_to?(:bar, true)
请注意,第二个参数在这里很重要 - 它表示:respond_to?
应该查找所有作用域方法,包括私有方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)