/ RAILS

Ruby Detect vs Select method on Enumerable

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

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.

array = [2, 4, 34, 65, 754, 72456]

Now, let’s say we want to find a number greater than 100.

This can be obtained using detect as given below.

array.detect{ |element| element > 100 }
# => 754

So, detect stop iteration over enumerable, as soon as element sastisfying condition is found.

Select

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.

array = [2, 4, 34, 65, 754, 72456]

And we want to find elements greater than 100.

It can be obtained with select as given below.

array.select { |element| element > 100 }
# => [754, 72456]

As we can see, the result is an array and it has elements greater than 100.

Conclusion

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

References

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee