Skip to content

Instantly share code, notes, and snippets.

@jmartelletti
Created September 17, 2014 09:46
Show Gist options
  • Select an option

  • Save jmartelletti/93795edac1d7e4c8f764 to your computer and use it in GitHub Desktop.

Select an option

Save jmartelletti/93795edac1d7e4c8f764 to your computer and use it in GitHub Desktop.
Ruby silently evaluating to the wrong value?
ERROR = "error"
STOPPED = "stopped"
RUNNING = "running"
state = ERROR
desired = STOPPED
([RUNNING].include? state) || (state == ERROR && desired == STOPPED)
[RUNNING].include?(state) || (state == ERROR && desired == STOPPED)
[RUNNING].include? state || (state == ERROR && desired == STOPPED)
(state == ERROR && desired == STOPPED) || [RUNNING].include?(state)
(state == ERROR && desired == STOPPED) || [RUNNING].include? state
irb(main):001:0> ERROR = "error"
=> "error"
irb(main):002:0> STOPPED = "stopped"
=> "stopped"
irb(main):003:0> RUNNING = "running"
=> "running"
irb(main):004:0>
irb(main):005:0* state = ERROR
=> "error"
irb(main):006:0> desired = STOPPED
=> "stopped"
irb(main):007:0>
irb(main):008:0* ([RUNNING].include? state) || (state == ERROR && desired == STOPPED)
=> true
irb(main):009:0> [RUNNING].include?(state) || (state == ERROR && desired == STOPPED)
=> true
irb(main):010:0> [RUNNING].include? state || (state == ERROR && desired == STOPPED)
=> false
irb(main):011:0> (state == ERROR && desired == STOPPED) || [RUNNING].include?(state)
=> true
irb(main):012:0> (state == ERROR && desired == STOPPED) || [RUNNING].include? state
SyntaxError: (irb):12: syntax error, unexpected tIDENTIFIER, expecting end-of-input
from /Users/james/.rubies/ruby-2.1.2/bin/irb:11:in `<main>'
@freshtonic
Copy link
Copy Markdown

I think it's because || has higher operator precedence than ( and ).

But I'm too lazy to check ;)

@freshtonic
Copy link
Copy Markdown

So this:

[RUNNING].include? state || (state == ERROR && desired == STOPPED)

Is equivalent to:

[RUNNING].include?(state || (state == ERROR && desired == STOPPED))

@freshtonic
Copy link
Copy Markdown

This also happens in coffeescript I believe.

@JonRowe
Copy link
Copy Markdown

JonRowe commented Sep 17, 2014

@freshtonic is correct, the slight weirdness is caused by the boolean on one side parsing correctly. [RUNNING].include? state || [RUNNING].include? desired would also error

@jmartelletti
Copy link
Copy Markdown
Author

Thanks for getting to the bottom of that!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment