Refactoring with Ruby

Robert Rosenberg
3 min readFeb 19, 2018

--

In ruby, it’s possible to take a piece of code that spans multiple lines and break it down all into only a couple lines of code or even one! In this post we’ll look at how to do this with a standard if else statement. I hope this helps outline a way to go about refactoring code and utilizing the powerful methods ruby has at its disposal.

Here’s a simple ruby challenge we’ll solve and then refractor ( I got this problem from my instructor at Actualize.co)

Write a method called “sum_of_range”, which will accept an array containing two numbers, and return the sum of all the whole numbers within the range of those numbers, inclusive.

This question isn’t too hard but there are many ways to answer this question. So let’s try to write the simplest form of it first!

Here’s an answer, go ahead and run it if you’d like!

def sum_of_range(array)  total = 0  if array[0] < array[1]    i = array[0]    while i <= array[1]      total += i      i += 1    end  else    i = array[0]    while i >= array[1]      total += i      i -= 1    end  end  totalendp sum_of_range([1,5]) # => 15p sum_of_range([5,1]) # => 15p sum_of_range([6,2]) # => 20

Let’s break down the code

First I initialized a variable then had to write a conditional if else statement to deal with anyone trying to iterate backwards.

Inside each conditional, I wrote a while loop to ensure I added the correct numbers to the total. Then I returned the total.

We can all admit I’m not writing the code to get us to Mars, yet without the use of helpful methods, it still took me about 5 minutes to write out and a total of 17 lines of code.

Are you ready to see how incredible ruby is…..? Here’s a gif of the code be refactored to one line

Cool, huh?!

In this code, we used what’s called a ternary operator. To utilize it you must write the condition, in this case, if array[0] is smaller than array[1] if it’s true everything before the colon will be executed. Otherwise, everything after it will be executed.

We also used a couple methods to help clean things up. First was the reduce method. This method is an enumerator and in this case, will iterate through each item in the array and add it to the previous!

Last, we used .downto this makes it so we can iterate down in case the first number entered was bigger than the second!

In Conclusion

We took a huge chunk of code and broke it down into a single line. Now I must admit this isn’t the end-all solution to every problem. Some things are better coded with extra lines for readability. The purpose of this exercise was to show what a couple methods can do in tandem with the ternary operator!

Thanks for Reading

— Robert Rosenberg

--

--