detect and select method in ruby

Posted . Visible to the public.

detect method in ruby returns the first item in the collection for which the block returns TRUE and returns nil if it doesn't find any. It has an optional argument containing a proc that calculates a “default” value — that is, the value to return if no item in the collection matches the criteria without returning nil.

find is the alias for detect and find_all is an alias for select.

[1,2,3,4,5,6,7].detect { |x| x.between?(3,6) }
# 3
[1,2,3,4,5,6,7].select { |x| x.between?(3,6) }
# [3,4,5,6]
[1,2,3,4,5,6,7].find { |x| x.between?(13,61) }
# nil
[1,2,3,4,5,6,7].find(proc_obj) { |x| x.between?(13,61) }
# returns the value of proc_obj.call

detect / find stops iterating after the condition returns true for the first time. detect is a method of Enumerable.

on the other hand, select / find_all will iterate until the end of the input list is reached and returns all of the items in an array for which the block returned true.

Sandheep
Last edit
Posted by Sandheep to Sandheep's deck (2013-04-26 08:11)