6

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
Community
  • 1
  • 1
surajz
  • 3,471
  • 3
  • 32
  • 38

3 Answers3

9

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.

Daniel Pittman
  • 16,733
  • 4
  • 41
  • 34
  • so if the first statement will evaluate to something like ("[" || line.strip.empty?) = "[" and then (line.start_with? "["). – surajz Mar 08 '12 at 18:36
  • 1
    Exactly so. Precedence is a way of guessing what you meant when you leave out, eg, brackets. Just like math precedence works. – Daniel Pittman Mar 08 '12 at 18:38
3

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. :-)

Ricardo Acras
  • 35,784
  • 16
  • 71
  • 112
1

Daniel is right, more clearly:

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

will produce yes

megas
  • 21,401
  • 12
  • 79
  • 130