5

Is it true that in most cases, in Ruby, it is best to use &&, || instead of and, or, unless it is some special situations.

I think one of Ruby's design principles is to have least surprises as possible, so using and, or or actually have some surprises... such as and not having a higher precedence than or, while && has a higher precedence than ||.

So I think in most cases, use &&, ||. In know in some special situations, it may require using and, or, but I think if those are intermixed with &&, ||, sooner or later it may create bugs when your coworkers who started in Ruby not so long ago need to edit your code.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

3 Answers3

7

Yes. Relying on and and or for boolean logic is a good way to introduce subtle bugs into your application.

They do have a place, though. They are a safe and readable option when used as control flow operators.

redirect_to root_url and return

I basically felt the way you did until I read this excellent blog post.

Raphomet
  • 3,589
  • 1
  • 23
  • 12
  • 1
    This is an awesome post, thanks for sharing. – Chuck Vose Sep 29 '10 at 23:04
  • 1
    Misunderstanding or misusing `and`, `or`, and `&&` and `||` is a problem in many languages. People assume (wrongly) that they are interchangable, ignoring the precedence of each. Like Raphomet says, not knowing when to use each one leads to subtle bugs. I agree that the best use of `and` and `or` is as a flow-control, leading to more readable code. Liberal use of `(` and `)` can go a long ways to avoid the problem too, though it can lead to code that looks like line noise... or Perl. – the Tin Man Sep 30 '10 at 00:19
7

The book 'The Ruby Programming Language' (David Flanagan & Yukihiro Matsumoto) gives two reasons to use 'and'.

  • readability:

    if x > 0 and y > 0 and not defined? d then d = Math.sqrt(x*x +y*y) end

  • make good use of the lower precedence:

    if a = get_from_db(x) and b = get_from_db(y) then do_stuff_with_true_values(a, b) end

(code adapted by me) The last one just wouldn't work with '&&'.

Personally, I use 'and' and 'or' combined with parentheses in case of doubt, for readability.-

steenslag
  • 79,051
  • 16
  • 138
  • 171
2

It's because and, or & not have lower precedence than &&, || and !.

Why? Because it stems from Perl. Larry Wall being a linguist wanted the following to work:

open my $fh, "<", $filename or die $!;

If you replace the or with || then that statement would be parsed like this:

open my $fh, "<", ($filename || die $!);

Which is not good!

So for languages like Perl & Ruby where parenthesis are often optional then this was the solution. Otherwise you would need to write:

open( my $fh, "<", $filename ) || die $!;

See perlop "Logical Not, And, or, Defined or, and Exclusive Or && Logical operators in Perl and Ruby for the full shake down.

/I3az/

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
draegtun
  • 22,441
  • 5
  • 48
  • 71