method
detect
![Wide documentation Importance_3](https://d2vfyqvduarcvs.cloudfront.net/images/importance_3.png?1349367920)
Ruby latest stable (v2_5_5)
-
1 note -
Class: Enumerable
detect(p1 = v1)
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 otherwise.
If no block is given, an enumerator is returned instead.
(1..100).detect => #<Enumerator: 1..100:detect> (1..100).find => #<Enumerator: 1..100:find> (1..10).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> nil (1..10).find { |i| i % 5 == 0 and i % 7 == 0 } #=> nil (1..100).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> 35 (1..100).find { |i| i % 5 == 0 and i % 7 == 0 } #=> 35
Register or
log in
to add new notes.
Alex -
August 15, 2008
![Default_avatar_30](https://www.gravatar.com/avatar/716d2bee319e8ed3040dc5d0a1ce74d5?size=30&default=http://apidock.com/images/default_avatar_30.png)
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"