The priority of the arguments of the method and / or method in ruby

Here are two tests:

if [1,2,3,4].include? 2 && nil.nil? puts :hello end #=> 

and

 if [1,2,3,4].include?(2) && nil.nil? puts :hello end #=> hello 

It is said above that && has a higher priority than the arguments of the method, so is it logical and 2 && nil.nil? , which is true, and passes it as an argument to include ?.

However, there is such a test:

 if [1,2,3,4].include? 2 and nil.nil? puts :hello end #=> hello 

So, this tells me that the method arguments and " and " have the same priority (or the method arguments are higher than the " and ") since it passed 2 to be included? before processing "and".

Note. I understand that && and and have a different priority. The question is not this, but with respect to and or or against the arguments of the ruby ​​method.

I can not find documentation to confirm this. For instances, this does not mention the method arguments at all: http://phrogz.net/programmingruby/language.html#table_18.4 or http://romhack.wikia.com/wiki/Ruby_operators .

Can anyone explain this behavior? Namely, how is it known that Ruby passes values ​​as arguments to a method or process operators?

+7
ruby operator-precedence
source share
2 answers

As you said, && and and have different priorities, however the explanation is for the following example:

 if [1,2,3,4].include? 2 and nil.nil? puts :hello end #=> hello 

is the strength of the and binding, which you can read here: The difference between "and" and && in Ruby?

This basically explains what 2 and nil.nil? will evaluate to nil, however it will return 2, as shown in this example:

 foo = :foo bar = nil a = foo and bar # => nil a # => :foo a = foo && bar # => nil a # => nil 
+1
source share

I have never seen the documentation about the priority of a method argument, but one rule that I use when looking at method arguments is to mentally break the spaces where possible in the arguments and still have the same expression. This usually gives me priority:

[1,2,3,4].include? 2&&nil.nil? is the same expression, but you cannot [1,2,3,4].include? 2 and nil.nil? [1,2,3,4].include? 2 and nil.nil? and therefore, priority from left to right ... Ie The argument to the method is 2.

Anyway, the best question is why would you write such statements?

Omitting method labels is only useful for reading code. However, your statements are hardly readable and pause over the code and think more about it than necessary. If I looked at such code, I certainly would not be able to check the code due to poor readability.

In fact, many style guides explicitly indicate that most methods with arguments should be enclosed in brackets (this is even a word;). For example: Ruby Style Guide

0
source share

All Articles