Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to use parenthesis in ruby function call before logical operator?

Tags:

ruby

''.instance_of?(String) && 0 == 0 is true, however

''.instance_of? String && 0 == 0 gives TypeError: class or module required

Do I have to use parenthesis before &&, or is it a bug?

like image 626
dimid Avatar asked Dec 05 '25 03:12

dimid


1 Answers

It is not a bug. The two things just mean different things.

The gist of it is that the && and || logical operators have higher precedence than method invocation. So what happens is the instance_of? method is being called with the result of String && 0 == 0, which is true. true is not a class, hence the error.

On the other hand, and and or have lower precedence, therefore

''.instance_of? String and 0 == 0

would work the way you expected it to.

In this scenario, it is best to put the parenthesis.

like image 161
ndnenkov Avatar answered Dec 09 '25 02:12

ndnenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!