RailsConf 2008

Using && or and in Ruby

May 11, 2006 10 comments
Two reasons why I use && in my code:

a = 'test'
b = nil
both = a && b       # both == nil
both = a and b      # both == 'test'
both = (a and b)    # both == nil
One reason why using and is better:
  • It reads well

You will get bitten very hard (I have more times than I care to recall) if you don’t pay close attention to which one you’re using, so I prefer using && everywhere now.

10 comments


Olav said 10 days later:

Thanks for the tip!

Peter Cooper said 15 days later:

Operator precedence can throw up some interesting problems in most languages :)

finn said about 1 month later:

This is Ruby showing its Perl roots. The addition of the extremely low precedence “and” and “or” operators was intended to aid program control flow. The sections C-style Logical Or and Logical Or and Exclusive Or in the perlop manpage have some more background.

Carl said about 1 month later:

I’m not sure that a valid reason for using ‘and’ over ‘&&’ is the fact you don’t understand operator precedence.

‘and’ has very low precedence, so ‘both = a and b’ is equivalent to ‘(both = a) and b’.

Orion said about 1 year later:

A good rule of thumb I find is to use ‘&&’ for manipulating values (as you do above) and to use ‘and’ for control flow in if blocks and so on where it can’t bite you.

it can bite you if you do things like “if a = c and d” but you really should know better than to write ambiguous code like that in the first place!

Orion said about 1 year later:

A good rule of thumb I find is to use ‘&&’ for manipulating values (as you do above) and to use ‘and’ for control flow in if blocks and so on where it can’t bite you.

it can bite you if you do things like “if a = c and d” but you really should know better than to write ambiguous code like that in the first place!

Orion said about 1 year later:

A good rule of thumb I find is to use ‘&&’ for manipulating values (as you do above) and to use ‘and’ for control flow in if blocks and so on where it can’t bite you.

it can bite you if you do things like “if a = c and d” but you really should know better than to write ambiguous code like that in the first place!

Orion said about 1 year later:

A good rule of thumb I find is to use ‘&&’ for manipulating values (as you do above) and to use ‘and’ for control flow in if blocks and so on where it can’t bite you.

it can bite you if you do things like “if a = c and d” but you really should know better than to write ambiguous code like that in the first place!

Orion said about 1 year later:

PS: Please put a progress indicator or something on the ajax comment submitting :-(

I hit ‘submit comment’ and nothing happened, so I hit it again a couple of times, and then 2 seconds later I have four comments :-(

Anil Wadghule said about 1 year later:

Nice info! I came to this post from http://github.com/rails/rails/commit/162c7c1908946cfb48c201cfc5a4976a33c8bff1.

Name
Url