Flowdock
detect(...) public

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil

   (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
   (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35
Show source
Register or log in to add new notes.
August 15, 2008
8 thanks

Optional Argument for detect/find [Not Documented]

detect/find’s optional argument lets you specify a proc or lambda whose return value will be the result in cases where no object in the collection matches the criteria.

classic_rock_bands = ["AC/DC", "Black Sabbath","Queen", "Ted Nugent and the Amboy Dukes","Scorpions", "Van Halen"]
default_band = Proc.new {"ABBA"}
classic_rock_bands.find(default_band) {|band| band > "Van Halen"}
=> "ABBA"

or

random_band = lambda do
  fallback_bands = ["Britney Spears", "Christina Aguilera", "Ashlee Simpson"]
  fallback_bands[rand(fallback_bands.size)]
end
classic_rock_bands.find(random_band) {|band| band > "Van Halen"}
=> "Britney Spears"