boolean operators trouble in ruby

Problem: We had a line like “errors = errors or hash.key? (:symbol)” and errors just wouldn’t  become “true”, even if the expression “errors or hash.key? (:symbol)” evaluated to “true”.

Solution: You have use “errors = (errors or hash.key? (:symbol))” or probably “errors = errors || hash.key? (:symbol)” .

Explanation: The keyword is operator precedence. It seems the “=”-operator has a higher precedence than the “or”-operator, so the line is evaluated as if one writes “(errors = errors) or hash.key? (:symbol)”. That means ruby just assigns “errors” to “errors” and then evaluates the whole statement. By using parentheses or the “||”-operator the right side of the “=”-operator has a higher precedence and is evaluated first, then assigned to the left side.

References: Here is where we found the solution: http://adamloving.com/internet-programming/ruby-boolean-operator-or-ruby-parsing-bug

Advertisements
This entry was posted in Ruby. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s