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

Aly*_*Aly 3 ruby ruby-1.9

当我写下面这一行时:

if (collection.respond_to? :each && collection.respond_to? :to_ary)
Run Code Online (Sandbox Code Playgroud)

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

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

if ((collection.respond_to? :each) && (collection.respond_to? :to_ary))
Run Code Online (Sandbox Code Playgroud)

&&改为and:

if (collection.respond_to? :each and collection.respond_to? :to_ary)
Run Code Online (Sandbox Code Playgroud)

任何想法为什么会这样?此外之间有什么区别&&and

谢谢

Mar*_*rth 7

&&具有高优先级(强于and,强于=).

foo = 3 and 5 # sets foo = 3
foo = 3 && 5  # sets foo = true
Run Code Online (Sandbox Code Playgroud)

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

 if (collection.respond_to? :each && collection.respond_to? :to_ary)
 if (collection.respond_to? (:each && collection.respond_to?) :to_ary)
Run Code Online (Sandbox Code Playgroud)

这没有任何意义.虽然使用and解析是这样的

 if (collection.respond_to? :each and collection.respond_to? :to_ary)
 if (collection.respond_to?(:each) and collection.respond_to?(:to_ary))
Run Code Online (Sandbox Code Playgroud)

我建议你使用这个(因为它不依赖于运算符优先级规则,并且使用最少的大括号,具有最短的大括号距离,以及andif条件中更常见的使用&&):

 if collection.respond_to?(:each) and collection.respond_to?(:to_ary)
Run Code Online (Sandbox Code Playgroud)