13

First of all I found two useful articles in documentations about these methods:

all?: Passes each element of the collection to the given block. The method returns true if the block never returns false or nil.

any?: Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil.

But in case of empty arrays and hashes I got:

irb(main):004:0> [nil, "car", "bus"].all?
=> false
irb(main):005:0> ["nil", "car", "bus"].all?
=> true
irb(main):006:0> [].all?
=> true
irb(main):007:0> ["nil", "car", "bus"].any?
=> true
irb(main):008:0> [nil, "car", "bus"].any?
=> true
irb(main):009:0> [nil].any?
=> false
irb(main):010:0> [].any?
=> false

Can somebody explain to me why empty arrays give me false in case of the any? method and true in case of all??

Community
  • 1
  • 1
y4roslav
  • 347
  • 1
  • 3
  • 10
  • 4
    In mathematical terms: `any?` is a fold of logical OR whose identity element is `false`. On the other hand `all?` is a fold of logical AND, whose identity element is `true`. http://en.wikipedia.org/wiki/Identity_element – tokland Nov 06 '12 at 15:44

1 Answers1

16

The method returns true if the block never returns false or nil.

So since the block never gets called, of course it never returns false or nil, thus all returns true.

The same goes for any:

The method returns true if the block ever returns a value other than false or nil.

Since the block never gets called, it never returns a value other than false or nil, thus any returns false.

mikej
  • 65,295
  • 17
  • 152
  • 131
Kim Stebel
  • 41,826
  • 12
  • 125
  • 142