在 Ruby 中,如何检查方法“foo=()"是否正确?被定义为? [英] In Ruby, how do I check if method "foo=()" is defined?
本文介绍了在 Ruby 中,如何检查方法“foo=()"是否正确?被定义为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Ruby 中,我可以定义一个方法 foo=(bar):
In Ruby, I can define a method foo=(bar):
irb(main):001:0> def foo=(bar)
irb(main):002:1> p "foo=#{bar}"
irb(main):003:1> end
=> nil
现在我想检查它是否已经定义,
Now I'd like to check if it has been defined,
irb(main):004:0> defined?(foo=)
SyntaxError: compile error
(irb):4: syntax error, unexpected ')'
from (irb):4
from :0
这里使用的正确语法是什么?我认为必须有一种方法可以转义 "foo=" 以便它被解析并正确传递给定义的?操作员.
What is the proper syntax to use here? I assume there must be a way to escape "foo=" such that it is parsed and passed correctly to the defined? operator.
推荐答案
问题在于 foo=
方法旨在用于分配.您可以通过以下方式使用 defined?
来查看发生了什么:
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"
比较:
def foo
end
defined?(foo)
#=> "method"
要测试是否定义了 foo=
方法,您应该使用 respond_to?
代替:
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
这篇关于在 Ruby 中,如何检查方法“foo=()"是否正确?被定义为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文