There is a subtle difference between Detect and Select method in Ruby. Select and detect both operate on Enumerable and require a condition to return the result. The primary difference between the two is as given below.
Detect requires a condition to be passed for evaluation. Detect iterates over each item in the enumerable to see which one satisfies the condition passed. As soon as, the condition is satisfied, enumerable returns that particular item. find is an alias for detect method. Thus, we can use find instead of detect as well.
e.g. Let’s consider an array to work with.
Now, let’s say we want to find a number greater than 100.
This can be obtained using
detect as given below.
So, detect stop iteration over enumerable, as soon as element sastisfying condition is found.
Select requires a condition to be passed for evaluation. Select iterates over each item in the enumerable, collects all the items matching the condition passed, and those are returned.
Thus, select returns an array.
Let’s consider the same example as above.
And we want to find elements greater than 100.
It can be obtained with select as given below.
As we can see, the result is an array and it has elements greater than 100.
1) detect - Finds and returns the first element matching condition.
2) select - Finds and returns all the elements matching the condition.
3) find - Finds and returns the first element matching condition. Internally calls detect
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox