Boolean Operators

M

Mark Dodwell

Quick question:

I know that the 'and' and 'or' operators in ruby have the same
precedence, and '&&' has a higher one than '||' - but is there a best
practise for which one to use when precedence isn't important?

Thanks,

~ Mark
 
R

Robert Klemme

I know that the 'and' and 'or' operators in ruby have the same
precedence, and '&&' has a higher one than '||' - but is there a best
practise for which one to use when precedence isn't important?

I usually use && and || because they visually stand out better than
"and" and "or" and can be used with assignments (higher precedence than
"="). I use "and" and "or" rather seldom mostly when chaining commands
as in

foo = doit() and puts foo

YMMV

Kind regards

robert
 
R

Rick DeNatale

I use "and" and "or" rather seldom mostly when chaining commands
as in

foo = doit() and puts foo

Keeping in mind that using && instead of and here has quite a
different result, even after adjusting the syntax of the puts call:

irb(main):001:0> a = 1 and puts "foo"
foo
=> nil
irb(main):002:0> a
=> 1
irb(main):003:0> a = 1 && puts "foo"
SyntaxError: compile error
(irb):3: syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
a = 1 && puts "foo"
^
from (irb):3
irb(main):004:0> a = 1 && puts("foo")
foo
=> nil
irb(main):005:0> a
=> nil

I don't know that I've ever used 'and' since being bitten by the
relative precedence of = and 'and' in a rails app I inherited and was
extending.

I also don't believe that I'd personally use
a = 1 and puts "foo"

rather than splitting it into two lines, perhaps replacing the and
with a semi-colon or otherwise steppng back and micro-refactoring the
code to make it clearer.

But I could be wrong.
 
R

Robert Klemme

Keeping in mind that using && instead of and here has quite a
different result, even after adjusting the syntax of the puts call:

Which is the precise reason why I would use "and" in this case. Note
that I wrote "seldom" so this is not a too frequent idiom I employ.
rather than splitting it into two lines, perhaps replacing the and
with a semi-colon or otherwise steppng back and micro-refactoring the
code to make it clearer.

But I could be wrong.

I don't think so. This is also a question of personal style and I don't
find anything wrong with your approach.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top