Eliah Hecht <eliahhecht / gmail.com> writes:

> I was working on an assignment for my Algorithms & Data Structures
> class when I determined that I had a need to figure out whether an
> array was (a) empty, or contained nothing but nils and things that I
> want to consider nil, or (b) contained non-nil-esque items. So I was
> pleasantly surprised to discover Array#nitems; I thought to myself,
> "I'll just make nil-like things respond true to nil?". However, this
> didn't seem to work: it appears that Array#nitems checks whether the
> array elements == nil, not whether they respond true to nil?. It seems
> to me that a nil?-based approach would be more productive, allowing
> greater flexibility in terms of what counts as an item.
>
> In case I'm being unclear, if I do
> class Thing
>   def nil?
>     true
>   end
> end
> t = Thing.new
> I think it should be the case that [t, nil, 7].nitems returns 1,
> instead of 2 as it currently does.

Well, the documentation says "non-nil items", and that means things
that aren't nil.  :) Checking for the exact value nil is quicker than
using a user-defined criterion.  #any? and #all? are good for what
you're trying to do.