Ruby 1.9.2 Object.respond_to? :你好&& Object.hello 报错,为什么?
今天单步调试代码时,我注意到一些意想不到的事情。这个语句:
if Object.respond_to? :你好&&对象.hello #stuff
给出未定义的方法错误。但为什么?显然 hello 不是 Object 的有效方法,但是考虑到短路评估,每当 Object.respond_to 时是否都应该忽略 Object.hello ? : 你好是假的吗?
我在玩 Authlogic 时注意到了这一点,试图弄清楚为什么 UserSession 类必须定义持久化?在 Rails 3 中。
谢谢
While stepping through code today, I noticed something unexpected. This statement:
if Object.respond_to? :hello && Object.hello
#stuff
gives an undefined method error. But why? Obviously hello is not a valid method of Object, however given the short-circuit evaluation, shouldn't Object.hello be ignored whenever Object.respond_to? :hello is false?
I noticed this while playing with Authlogic, trying to figure out exactly why the UserSession class must define persisted? in Rails 3.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
缺少括号会导致优先级问题:
The lack of parentheses is leading to a precedence issue:
您遇到优先级问题,逻辑连接 (
&&
) 的优先级高于方法调用,因此您的示例是这样执行的:而不是这样:
这就是您所假设的。
You have a precedence problem, the logical conjunction (
&&
) has a higher precedence than the method call so your example is executed like this:not like this:
which is what you're assuming.
我相信您遇到了评估顺序问题。考虑以下几点:
I believe you are running into an evaluation order problem. Consider the following:
如果您使用 if 语句检查某些内容的条件,那么您正在寻找布尔响应。 Object.hello 不会返回 false,因为该方法不存在。您的检查:
正在检查该响应。我选择第二个 Object.hello 应该没有任何理由。
If you are checking the condition of something with an if statement you are looking for a boolean response. Object.hello doesn't return false because the method doesn't exist. Your check of:
Is checking for that response though. There shouldn't be any reason, in my option for the second Object.hello.