Skip to content

Instantly share code, notes, and snippets.

@sandheepg
Created March 8, 2017 07:37
Show Gist options
  • Save sandheepg/ab6a9af720e6dd46171dd8090d8cde83 to your computer and use it in GitHub Desktop.
Save sandheepg/ab6a9af720e6dd46171dd8090d8cde83 to your computer and use it in GitHub Desktop.
Difference between detect and select methods in ruby

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment