I often see people writing code like this:
Fixnum#even? would have been a better choice:
There is also
Fixnum#odd? if you need to check for odd numbers.
By the way, there is even a
1 2 3 4
Personally I feel that
x == 0 makes more sense for such simple
numeric checks, but
zero? is there for those you who think
x == 0 also has the benefit of being
nil safe, but
that’s not of significant importance.
The Powerpack library also
includes the predicate methods
are roughly the same as
> 0 and
< 0 comparisons.
Another bit of code you’ll often see is:
While there is nothing particularly bad about that code, I’d argue
between? makes for a nicer (and more OO) alternative:
Using a range predicate you can also exclude the end value:
1 2 3 4
When using predicate methods you should be mindful of
receivers. That’s generally not a serious issue in practice but still I’d ask
you to consider this example:
It’s not equivalent to
Why so? Because
arr might be
nil. So the equivalent code would be:
Of course checking for
nils like this is generally not a good idea, but
that’s a discussion for some other time.
On a somewhat related note
something.nil? is generally preferred
something == nil. If you’re reasonably sure that
can’t have the value
false you can, of course, simplify things even
As usual I’m looking forward to hearing your thoughts here and on Twitter!