Politics, Programming and Possibilities
17 Apr
This one got me today:
feed_bridge_is_valid = !state[:feed] or (state[:feed] and @feed_bridge.valid?)
It turns out that the “=” assignment has a higher precedence than the “or” operator, so if (in the example above) !state[:feed] turns out to be false then feed_bridge_is_valid will be assigned a false value, and the entire expression will return the value of (state[:feed] and @feed_bridge.valid?).
Here’s one solution:
feed_bridge_is_valid = (!state[:feed] or (state[:feed] and @feed_bridge.valid?))
And I think you can also solve the problem by using the “||” version of the “or” operator too.
2 Responses for "Ruby Gotcha: "or" Precedence"
[...] Came across this helpful post from Duane in which he explains an important difference between the && and || operators from the nicer-looking “and” and “or” operators. [...]
Yeah if you want to stick with poetry mode without parens then you should always use || and && instead of or & and. The precedence makes a bit more sense to me using the symbols. They bind tightewr then or & and.
Leave a reply