Using && or and in Ruby
May 11, 2006
10 comments
Two reasons why I use && in my code:
- The Rails source does
- I learned to program in C++ so the following is downright scary
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.
Thanks for the tip!
Operator precedence can throw up some interesting problems in most languages :)
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.
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’.
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!
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!
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!
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!
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 :-(
Nice info! I came to this post from http://github.com/rails/rails/commit/162c7c1908946cfb48c201cfc5a4976a33c8bff1.