Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby boolean operator or || difference [duplicate]

Tags:

ruby

Possible Duplicate:
Ruby: difference between || and 'or'

In ruby, isn't 'or' and '||' the same thing? I get different results when I execute the code.

line =""
if (line.start_with? "[" || line.strip.empty?)
  puts "yes"
end




line =""
if (line.start_with? "[" or line.strip.empty?)
  puts "yes"
end
like image 812
surajz Avatar asked Mar 08 '12 18:03

surajz


2 Answers

No, the two operators have the same effect but different precedence.

The || operator has very high precedence, so it binds very tightly to the previous value. The or operator has very low precedence, so it binds less tightly than the other operator.

The reason for having two versions is exactly that one has high precedence and the other has low precedence, since that is convenient.

like image 167
Daniel Pittman Avatar answered Oct 12 '22 23:10

Daniel Pittman


In the first case you used || wich is evaluated prior than anything else in the statement due to the precedence well stated by other answeres, making it clearer with some parenthesis added, your first statement is like:

(line.start_with? ("[" || line.strip.empty?))

wich translates to

(line.start_with? ("["))

resulting FALSE

In the other hand, your second statement translates to

((line.start_with? "[") or line.strip.empty?)

wich translates to

(FALSE or TRUE)

resulting true

That´s why I try to use parenthesis everytime I call a function. :-)

like image 37
Ricardo Acras Avatar answered Oct 13 '22 00:10

Ricardo Acras