Yesterday I introduced a bug in one of my scripts after accidentally
deleting av space. It took me quite I while to find where the bug was,
but I still can’t understand why the missing space leads to a
different result. Anyone out there that can explain it to me?
Removing the space causes the minus to be interpreted as a unary
negative
operator rather than the binary minus that you get with the space. The
unary operator has a relatively higher precedence than the binary minus
and
more importantly than the dot operator used for invoking #count on your
array, so it changes the expression evaluation completely – first,
evaluating the unary negative operator on 1, and then passing the result
as
an argument to #count. Because Array#count can take an argument that
says,
“count how many of this thing I have in my array”, you get 0 as your
output
because your array has no -1 elements. See how the result changes below
when I begin adding -1’s to my array.
It seems like I’ve been using ruby for six years without ever
realizing that Enumerable.count behaved differently than
Enumerable.length or Enumerable.size. Those nifty enumerators usually
make it unnecessary to deal with the index at all.
I’ll just switch to Enumerable.size for now. That will give me an
argument error if I’ll ever drop that space again.
Thanks again for enlightening me!
/lasso
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.