I love Ruby!
I love Ruby! I love it for the same reason I also enjoy programming with Python. It is so intuitive and the built-in methods make problem solving so easy. If you are ever wondering, “is there a method for that?”, there probably is.
You don’t necessarily need to use Ruby’s built in methods, but there are so many of them, and you can even chain them together to reach your desired outcome. These built in methods can help you cut down on programming length, turning something that would have taken 5–6 lines down to 1.
Below I’ve given a few examples of how ruby code can be refactored using these methods for more streamlined programming.
First, here is a basic loop to find the word “needle” and return the index where that word was found in an array:
Here is now an example of how that can be refactored using Ruby’s built in .index method to return that same information:
In this next example the goal is to sum the smallest values from a 2D array, or find the sum of the minimum values in each row. The basic loop solution might look like this:
And here is the refactored solution which uses the built in .sum method and interjects the .min method to find the smallest number from each array:
There are a few ways to find these available methods. You can use google, of course. If you tack on .methods to a class, like String.methods, you will get returned a list of available methods. You can also check out https://ruby-doc.org/core-2.3.1/ for up to date information.
Give some refactoring a try, I hope you come to like Ruby as much as I do!