Bartek Gładys Bartek Gładys - 1 year ago 73
Ruby Question

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

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

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

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download