Using Detect and Select

Flatiron School / 31 October 2012

The following is a guest post by James Vanneman and originally appeared on his blog. James is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

If you find yourself writing cumbersome each loops with a bunch of if/else statements to modify elements of an array, you can probably simplify your code. Detect and select are higher level iterators that can take complicated each statements and transform them into something much more concise. At first glance the methods are very similar but they have some key distinctions that make them useful in different situations.

Select takes blocks that can contain inequalities and returns new arrays based on them. If a single element is selected, it will return a 1 item array of that element.

Detect only returns single values from an array that match the block. If an inequality is passed in it will return the first matching value. The detect function does not return an array, just the value that matches the block.

When no item is matched they return the following:

Select and detect help you avoid having to write complicated each blocks. I recently wrote code to parse a song playlist and return to me the artist and their song. If an artist didn’t exist, I wanted to create a new instance of that class. However if an instance of that artist had already been created, I wanted to return that object. I achieved this using the each method with the following code:

That’s a lot of code that isn’t easy to understand right away. Thankfully the detect and select method can make this much nicer. Using select the code becomes:

Since detect can return a falsy value, it’s more useful in a conditional block than select. The code can be refactored to a much cleaner version using detect.

Compared to the original each block, both refactorings are much more readable. The differences between the two are subtle but important to understand in order to use them effectively. The detect and select methods can be incredibly useful and help you avoid writing lots of logic within each statements.

How to Avoid Multitasking for Greater Productivity Previous Post How the Internet Works: Part 1 of 3 Next Post