繁体   English   中英

Ruby - 使用&&时的意外行为

[英]Ruby - unexpected behaviour when using &&

当我写下面这一行时:

if (collection.respond_to? :each && collection.respond_to? :to_ary)

我的IDE(Aptana Studio 3)给了我以下错误: , unexpected tSYMBEG

但是如果我添加括号,错误就会消失:

if ((collection.respond_to? :each) && (collection.respond_to? :to_ary))

或更改&& and

if (collection.respond_to? :each and collection.respond_to? :to_ary)

任何想法为什么会这样? 另外, && and ?有什么区别?

谢谢

&&具有高的优先级 (强于and比,更强= )。

foo = 3 and 5 # sets foo = 3
foo = 3 && 5  # sets foo = true

它也比模糊函数调用更强大。 您的代码将被解析

 if (collection.respond_to? :each && collection.respond_to? :to_ary)
 if (collection.respond_to? (:each && collection.respond_to?) :to_ary)

这没有任何意义。 使用and解析时

 if (collection.respond_to? :each and collection.respond_to? :to_ary)
 if (collection.respond_to?(:each) and collection.respond_to?(:to_ary))

我建议你使用这个(因为它不依赖于运算符优先级规则和使用最少的牙套,具有最短的大括号的距离,和用途and其往往是可以找到if不是条件&& ):

 if collection.respond_to?(:each) and collection.respond_to?(:to_ary)

因为Ruby是一种动态语言,所以ruby无法知道你是否使用符号作为整数(存储它们),因此'&&'运算符优先于函数调用,因此你实际上是在调用

collection.respond_to? (:each && collection.respond_to? :to_ary) collection.respond_to? (:each && collection.respond_to? :to_ary)而不是调用

(collection.respond_to? :each) and (collection.respond_to? :to_ary)

这是方法调用然后一个布尔逻辑运算符。 当使用'和'代替&&时,'和'具有更低的先行(低于函数调用),因此它也有效。

'和'和'或'vs'&&''||'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM