views:

231

answers:

3

It is really hard to google this, because neither || nor 'or' are good words to search for :)

I am wondering if there is a difference between the two, or if it is just a matter of preference?

+13  A: 

It's a matter of operator precedence.

|| has a higher precedence than or.

So, in between the two you have other operators including ternary (? :) and assignment (=) so which one you choose can affect the outcome of statements.

Here's the ruby operator precedence table.

See this question for another example using and/&&.

mopoke
+1  A: 

Just to add to mopoke's answer, it's also a matter of semantics. or is considered to be a good practice because it reads much better than ||.

rogeriopvl
I don't know if "good practice" is on the side of the or operator. The case is analogous to parens on arguments. Method calls often read nicer without, but they lead to strange bugs in certain cases. I used to selectively use or and drop parens, but eventually I just gave up on them because fairly often they could not be used, some of those times I forgot and introduced a bug, and came to prefer the consistency of just always using parens and ||.The situation is at least debatable.
floyd
you mean it's a matter of syntax :) they both have the same semantic interpretation (modulo operator precedence)
klochner
+6  A: 

As the others have already explained, the only difference is the precdence. However, I would like to point out that there are actually two differences between the two:

  1. and, or and not have much lower precedence than &&, || and !
  2. and and or have the same precedence, while && has higher precedence than ||

In general, it is good style to avoid the use of and, or and not and use &&, || and ! instead. (The Rails core developers, for example, reject patches which use the keyword forms instead of the operator forms.)

The reason why they exist at all, is not for boolean formulae but for control flow. They made their way into Ruby via Perl's well-known do_this or do_that idiom, where do_this returns false or nil if there is an error and only then is do_that executed instead. (Analogous, there is also the do_this and then_do_that idiom.)

Examples:

download_file_via_fast_connection or download_via_slow_connection
download_latest_currency_rates and store_them_in_the_cache

Sometimes, this can make control flow a little bit more fluent than using if or unless.

It's easy to see why in this case the operators have the "wrong" (i.e. identical) precedence: they never show up together in the same expression anyway. And when they do show up together, you generally want them to be evaluated simply left-to-right.

Jörg W Mittag
ephemient
Interesting, I didn't know that. I've never actively used Perl, nor learned it.
Jörg W Mittag
Good answer - I didn't know about the equal precedence thing, sounds like an accident waiting to happen.
klochner