The case equality operator === works like this:
2 === 2 #=> true
2 .=== 2 #=> true
To check how precedence and associativity work, I tried as below:
2 === 2 === 3
# SyntaxError: (irb):3: syntax error, unexpected tEQQ
# 2 === 2 === 3
# ^
# from C:/Ruby193/bin/irb:12:in `<main>'
Why did it return an error? The following does not raise an error. How does it resolve the error above?
2 .=== 2 === 3 #=> false
Ruby does not know which expression to evaluate first, so it throws an error. When you explicitly call the Integer#=== method with .===, Ruby will treat this as any other method call, which means that it assumes that everything to the right is an argument to that method. Due to these optional parentheses, you are actually writing in your last example:
2.===( 2 === 3 )
This expression in turn is not ambiguous and thus can be evaluated without errors.
Keep in mind that this will not return what you might expect; for example:
2.===( 2 === 2 )
#=> false
because the return value of the inner 2 === 2 is true. This is then compared to 2, and obviously 2.===(true) returns false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With