Created
September 17, 2014 09:46
-
-
Save jmartelletti/93795edac1d7e4c8f764 to your computer and use it in GitHub Desktop.
Ruby silently evaluating to the wrong value?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>' |
So this:
[RUNNING].include? state || (state == ERROR && desired == STOPPED)
Is equivalent to:
[RUNNING].include?(state || (state == ERROR && desired == STOPPED))
This also happens in coffeescript I believe.
@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
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
I think it's because
||
has higher operator precedence than(
and)
.But I'm too lazy to check ;)