In Ruby, how do I check if method “foo=()” is defined?

半城伤御伤魂 提交于 2019-11-30 04:08:59

The problem is that the foo= method is designed to be used in assignments. You can use defined? in the following way to see what's going on:

defined? self.foo=()
#=> nil
defined? self.foo = "bar"
#=> nil

def foo=(bar)
end

defined? self.foo=()
#=> "assignment"
defined? self.foo = "bar"
#=> "assignment"

Compare that to:

def foo
end

defined? foo
#=> "method"

To test if the foo= method is defined, you should use respond_to? instead:

respond_to? :foo=
#=> false

def foo=(bar)
end

respond_to? :foo=
#=> true

You can check if a method exists by using the respond_to? method, and you pass it a symbol, e.g. bar.respond_to?(:foo=) to see if the object bar has a method foo=. If you want to know if instances of a class respond to a method you can use method_defined? on the class (or module), e.g. Foo.method_defined?(:bar=).

defined? isn't a method, but an operator which returns a description of the operand (or nil if it is not defined, which is why it can be used in an if statement). The operand can be any expression, i.e. a constant, a variable, an assignment, a method, a method call, etc. The reason why it doesn't work when you do defined?(foo=) is because of the parentheses, skip them and it should work more or less as expected. That being said, defined? is a pretty weird operator, and no one uses it to test for the existence of methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!