Bartek Gładys Bartek Gładys - 2 months ago 6
Ruby Question

Diference beetwen detect{} and select{}[0]

I'm consider about diference beetwen these methods in ruby. I know,

select
returns an array of elements, and
detect
return only one and first consisten element. But is there any diference if i type
array.select{ condition }[0]
? It will return first unit like
detect
.
For example:

a = [2,3,4,5]
a.detect{|k| k.even? }
# => 2
a.select{|k| k.even? }[0]
# => 2


Anyone can explain me other distinctions beetwen these methods and give me some examples when
detect
will be better than
select
?

Answer

When you only need to retrieve one item, detect is preferable because it will stop iterating over the array when it finds the first occurrence matching the condition. Because select retrieves all occurrences that match the condition, it has to iterate over the entire list. In the worst case (where an item matching the condition is not in the list) these are equivalent, but if the item you are looking for is early in the list detect will be more performant.

Comments