I have this simple Ruby code that is processing command line arguments:
if !ARGV.length <= 2
print "clierr: please pass an arg"
client.rb:rb:1:in `<main>': undefined method `<=' for false:FalseClass (NoMethodError)
So why is it erroring?
This is not because
! is a method and you need to call it with parentheses. This is due to operator precedence or order of operations
In Ruby, all integers evaluate to
true, the only values that are evaluated to
nil, per the documentation. Now, let's look at your condition:
if !ARG.length <= 2
In this example,
! is the NOT operator. Performing this operation implicitly coerces it into a boolean for boolean operation. And since, as mentioned earlier,
ARGV.length is an integer, it is evaluated to
! happens first because
! has higher precedence than
!ARGV.length is evaluated, Ruby then reports that you are trying to do comparison on
false and an integer, that's illegal. You have to use grouping to control which operations happen when:
if !(ARGV.length <= 2)
The parentheses will tell Ruby to evaluate the condition inside the parentheses first, then continue evaluating, like order of operations. So, the inside is evaluation, then logical NOT happens.