Programmers in general and Rubyists, I think, in particular, revere elegance in code — which means clarity and brevity, along with (obviously) functionality. Needless repetition or complexity is called “code smell.” And in Ruby, if you find yourself taking multiple steps to do something very common — like go over an array to select values matching a certain condition, or to retrieve information to put into a new array — you can bet there’s a method that will let you do it in one elegant step. Here, I’ll be sharing some higher-level iterators along with the common “code smell” scenarios that signal that particular method should come in handy.
In Ruby, if you find yourself taking multiple steps to do something very common, you can bet there’s a method that will let you do it in one beautiful method call.
Code smell: You’re creating an empty hash or array. Then you’re iterating over another hash or array to retrieve information to put into your empty object. Then you’re returning your newly created object.
Code smell: You’re executing some action on a variable, and then have to return the variable in a separate step.
Code smell: You’re performing a mathematical function on a series of numbers (like adding or multiplying) and returning the result.