Often one must traverse a list or array of items to find and return the first instance with a certain property, attribute or id. For pattern matching in strings or texts, one would use regular expressions. For object matching in lists or arrays, usually one would write a function like this:

result = nil
instances.each do |instance|
  if instance.id == _id
    result = instance
    break
  end
end

With the detect method of the Enumerable module in Ruby this is quite easy. It returns the first object for which the passed block is true, for example the first element which is divisible by 5 and 7:

instances.detect{|instance| instance.id == _id}

(1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } 
=> 35
Advertisements