Search code examples
rubyoperator-precedence

Behaviour in regex validation


I tried to validate a path, and if the path doesn't match with the regex, then I applied a logic. I get the expected result in the following:

path = 'banner/gwd_preview_/index.html'
/^__MACOSX/.match(path).nil? and /gwd_preview_/.match(path).nil?
# => false

But when I store the regex validation in a variable:

is_valid_path = /^__MACOSX/.match(path).nil? and gwd_preview_/.match(path).nil?
# => false

and call for the result of is_valid_path, I get true:

is_valid_path # => true

Why does it happen?


Solution

  • = has stronger precedence than and. First, you assigned to is_valid_path the result of the first nil?, which turned out to be true. Then the second nil? returned false. The conjunction, then became false.