Last Updated: February 25, 2016
·
3.225K
· vumanhcuongit

Ruby methods: all? vs any?

all?:

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

["ant", "bear", "cat"].all? { |word| word.length >= 3 } #=> true
["ant", "bear", "cat"].all? { |word| word.length >= 4 } #=> false

any?:

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

["ant", "bear", "cat"].any? { |word| word.length >= 3 } #=> true
["ant", "bear", "cat"].any? { |word| word.length >= 4 } #=> true

Deep magic:

[].all? #=> true

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

[].any? #=> false

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