First of all I found two useful articles in documentations about these methods:
- http://www.ruby-doc.org/core-1.9.3/Enumerable.html
- http://www.globalnerdy.com/2008/01/29/enumerating-rubys-enumerable-module-part-1-all-and-any/
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??
So since the block never gets called, of course it never returns false or nil, thus
allreturns true.The same goes for
any:Since the block never gets called, it never returns a value other than false or nil, thus
anyreturns false.