Order of operations

  • Thread starter Jack Christensen
  • Start date
J

Jack Christensen

Just got bit by a little order of operations confusion.

irb(main):012:0> a = nil or 1
=> 1
irb(main):013:0> a
=> nil
irb(main):014:0> a = (nil or 1)
=> 1
irb(main):015:0> a
=> 1

Probably old news to long time rubyists but it surprised me. Is there
any way to get a warning or something when a statement like the above
may not be behaving like you would think?

Jack
 
D

Devin Mullins

I doubt this is the answer you're looking for, but if you use || instead
of or, the precedence is different. i.e. a = nil || 1 does what you
think it does.

Devin
 
R

Robert Klemme

Jack said:
Just got bit by a little order of operations confusion.

irb(main):012:0> a = nil or 1
=> 1
irb(main):013:0> a
=> nil
irb(main):014:0> a = (nil or 1)
=> 1
irb(main):015:0> a
=> 1

But note:
Probably old news to long time rubyists but it surprised me. Is there
any way to get a warning or something when a statement like the above
may not be behaving like you would think?

No, because Ruby cannot know what you expect. But note that there *are*
warnings:
(irb):3: warning: found = in conditional, should be ==
=> "ja"
"or" and "and" have much lower precedence than "||" and "&&" to give you
the choice and for example do things like

arr.empty? and puts "it's empty!"
a > 0 and puts "positive"

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

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top