Code Smell

Anna Rasshivkina
Feb 27, 2016 · 2 min read

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.

#each_with_object

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.

e.g:

Image for post
Image for post

#tap

Code smell: You’re executing some action on a variable, and then have to return the variable in a separate step.

e.g:

Image for post
Image for post

#inject

Code smell: You’re performing a mathematical function on a series of numbers (like adding or multiplying) and returning the result.

e.g:

Image for post
Image for post

Synaptic Sugar

Code blog covering Ruby, Javascript, HTML, CSS, and other…

Anna Rasshivkina

Written by

All things language. Writer, translator, coder. www.thesewords.live

Synaptic Sugar

Code blog covering Ruby, Javascript, HTML, CSS, and other assorted coding topics. Attempting to make simple the confusing, with minimum nerd jargon. Written by Anna Rasshivkina.

Anna Rasshivkina

Written by

All things language. Writer, translator, coder. www.thesewords.live

Synaptic Sugar

Code blog covering Ruby, Javascript, HTML, CSS, and other assorted coding topics. Attempting to make simple the confusing, with minimum nerd jargon. Written by Anna Rasshivkina.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store