Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precedence of and/or versus method arguments 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

The above tells me that && has higher precedence than method arguments so it logically ands 2 && nil.nil? which is true and passes that as an argument to include?.

However, there is this test:

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

So this is telling me that method arguments and 'and' have the same precedence (or method args are higher than 'and') since it passed 2 to include? before it processed 'and'.

Note: I understand that && and and have different precedence. The question is not regarding this but regarding and or or vs the arguments to a ruby method.

I can't find documentation that affirms this. For instances, this doesn't mention method arguments at all: http://phrogz.net/programmingruby/language.html#table_18.4 or http://romhack.wikia.com/wiki/Ruby_operators.

Could anyone explain this behavior? Namely in that how does ruby know to pass values as arguments to a method vs. process operators?

like image 287
jshort Avatar asked Jan 22 '15 18:01

jshort


1 Answers

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

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

is the binding strenght of the and as you can read here: Difference between "and" and && in Ruby?

This basically explains that 2 and nil.nil? will be evaluated as nil, however it will return 2 as can be seen in this example:

foo = :foo
bar = nil

a = foo and bar
# => nil
a
# => :foo

a = foo && bar
# => nil
a
# => nil
like image 101
Duncan Idaho Avatar answered Sep 28 '22 06:09

Duncan Idaho