From: John Sikora on
I find the following behavior interesting (so interesting that I
modified it), and I would like to hear others' thoughts on the subject:

[3].all? {|element| element == 3 } # => true
[3].all? {|element| element != 3 } # => false (sanity checks)

[].all? {|element| element == 3 } # => true
[].all? {|element| element != 3 } # => true

[].any? {|element| element == 3 } # => false
[].any? {|element| element != 3 } # => false

Ruby 1.8.6 and 1.9.1 both give these results.

The first interesting thing is that both the == and the != checks give
the same logical result (always true for all?, always false for any?).
After thinking about it a little, I decided that this is the desired

I also understand why it happens. For example, in the case of all?, the
documentation says that true will be the result if the block never
returns false or nil. In the case of [], the block never gets called, so
the result is true. I know the block never gets called because the
following does not print anything:

[].all? {|dummy| puts 'print something'}, while

[3].all? {|dummy| puts 'print something'} does.

The second interesting thing is that a result of this behavior is that
for the same check, all? will give a result of true, while any? will
give a result of false. This seems contradictory.

I would prefer that for [], both all? and any? would give a result of
false for any check. So I have over-ridden Array#all?, returning false
if self == []. My main motivation for doing so is in situautions such

obj_array.find_all{|obj| obj.attr_1 == x}.all?{|obj| obj.attr_2 == y}

If the find_all returns [], I want the all? result to be false, not

I assume that others have run across this but some quick searches did
not turn up anything. I am wondering how others deal with this such as
over-riding as I do, checking for [] each time (which does not seem very
Ruby-like), or even leaving the operation as is because for some, it may
be the desired behavior.

Finally, are there any potential detrimental effects that might occur
due to the behavior modification that I made. I am not a Rails user (if
that matters), I mainly use Ruby for scripting and hardware control
applications (and I am interested in learning as much as I can about
Ruby because I like it so much).

Posted via