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
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.
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With