Ruby Tuesday – Enumerable#any?

This weeks Ruby Tuesday entry covers Enumerable#any?.

Enumerable#any? takes a block and returns true if the block returns a truthy value for any of the elements in the enumeration, otherwise it returns false.

[1, 2, 3, 4, 5, 6].any? {|x| x.even?}
# => true
["foo", "bar", "snafu", "Snuffleupagus"].any? {|x| x.size > 10}
# => true
["foo", "bar", "snafu", "Snuffleupagus"].any? {|x| x.size < 2}
#=> false

The block is optional for Enumerable#any?, and if not specified, any uses the block {|obj| obj} by default.

[nil, nil, nil].any?
# => false
[false, nil].any?
# => false
[1, 2, 3].any?
# => true

Enumerable#any? is eager, so if it finds an element where the block evaluates to a truthy value it stops processing the rest of the enumerable.

Benchmark.realtime{  (1..20000000).lazy.select(&:even?).any?{|x| x.even? } }
# => 3.6e-05
Benchmark.realtime{  (1..20000000).lazy.select(&:even?).any?{|x| x.odd? } }
# => 5.709414

Ruby also has counterparts for any? which are Enumerable#all? and Enumerable#none?. These behave the similiar as Enumerable#any?, except that Enumerable#all? checks to that the return value of the block is truthy for all elements.

[1, 3, 5, 8].all?{|x| x.odd?}
# => false
[1, 3, 5, 81].all?{|x| x.odd?}
# => true
["foo", "bar", "snafu", "Snuffleupagus"].all?{|x| x.size > 10}
# => false
["foo", "bar", "snafu", "Snuffleupagus"].all?{|x| x.size > 2}
# => true
[true, true, true].all?
# => true
["false", true, true].all?
# => true
[true, true, nil].all?
# => false
[false, nil].all?
# => false

While Enumerable#none checks the that return value of the block is a falsey value for all elements.

[1, 3, 5, 7, 9].none?{|x| x.even?}
# => true
[1, 3, 5, 7, 8].none?{|x| x.even?}
# => false
[true, true, true].none?
# => false
[nil, nil, false, nil].none?
# => true

Both Enumerable#all? and Enumerable#none? are both eager as well.

Benchmark.realtime{  (1..20000000).lazy.select(&:even?).all?{|x| x.even? } }
# => 5.250464
Benchmark.realtime{  (1..20000000).lazy.select(&:odd?).all?{|x| x.even? } }
# => 3.3e-05
Benchmark.realtime{  (1..20000000).lazy.select(&:odd?).none?{|x| x.even? } }
# => 5.365924
Benchmark.realtime{  (1..20000000).lazy.select(&:even?).none?{|x| x.even? } }
# => 3.7e-05

–Proctor