1. Computing

Enumerable: Do Any or All Objects Match?

By

Another useful thing to do with collections is see if any or all of the elements match a certain criteria. For example, if I'm gathering temperature data, I want to sound an alarm if any temperature in an array is over 100 degrees. I want to shut down the system I'm monitoring if all of the temperatures in the sample are over 100 degrees.

The method get_sample will return some bogus temperature data, 10 samples at a time. This is then fed through the Enumerate#any? method, which takes a single block parameter. Each element of the collection is passed to this block. If it returns anything other than false or nil for any of the elements, the any? method will return true.

The all? method is similar, it will return true if the block returns anything other than false or nil for all of the elements.

#!/usr/bin/env ruby
require 'pp'

def get_sample
Array.new(10).map{rand(120)}
end

sample = get_sample
pp sample

puts "Temperature alarm!" if sample.any?{|o| o > 100}
puts "MELTDOWN! Shut down now!" if sample.all?{|o| o > 100}

©2014 About.com. All rights reserved.