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.
Written by Vu Manh Cuong
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#