在 Ruby 中,如何检查方法“foo=()”是否有效?被定义?
在 Ruby 中,我可以定义一个方法 foo=(bar)
:
irb(main):001:0> def foo=(bar)
irb(main):002:1> p "foo=#{bar}"
irb(main):003:1> end
=> nil
现在我想检查它是否已定义,
irb(main):004:0> defined?(foo=)
SyntaxError: compile error
(irb):4: syntax error, unexpected ')'
from (irb):4
from :0
这里使用的正确语法是什么?我认为必须有一种方法来转义 foo=
,以便它被解析并正确传递给 define?
运算符。
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于
foo=
方法被设计为在赋值中使用。您可以通过以下方式使用define?
来查看发生了什么:比较一下:
要测试
foo=
方法是否已定义,您应该使用respond_to?
改为:The problem is that the
foo=
method is designed to be used in assignments. You can usedefined?
in the following way to see what's going on:Compare that to:
To test if the
foo=
method is defined, you should userespond_to?
instead:您可以使用
respond_to?
方法检查方法是否存在,并向其传递一个符号,例如bar.respond_to?(:foo=)
来查看该对象是否存在bar
有一个方法foo=
。如果您想知道类的实例是否响应某个方法,您可以在类(或模块)上使用method_define?
,例如Foo.method_define?(:bar=)
。define?
不是一个方法,而是一个返回操作数描述的运算符(如果未定义则返回 nil,这就是它可以在 if 语句中使用的原因)。操作数可以是任何表达式,即常量、变量、赋值、方法、方法调用等。当您执行define?(foo=)
时它不起作用的原因是因为括号的原因,跳过它们,它应该或多或少按预期工作。话虽这么说,define?
是一个非常奇怪的运算符,没有人用它来测试方法是否存在。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 objectbar
has a methodfoo=
. If you want to know if instances of a class respond to a method you can usemethod_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 dodefined?(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.