Using Sort_by || Ruby

Simran Manandhar
2 min readDec 1, 2020

My CLI project was a success but it wasn’t yet polished. While searching for a category of an article, it would display in a random order. So, I wanted to display the articles in an alphabetical order.

This is where the ruby’s in built method sort_by is used. I knew that this method is used for sorting, but had to work for hours in order to get it to work. Firstly, I had been using it inside the each method. I used binding pry to go inside this iterator and tried sorting inside it. But I realized that each iterator would return the original array, so making any changes made no sense at all.

After I extracted the articles from the API, I converted it into object by passing the arguments (title, content, id and author) which then I passed to new on to the method initialize.

I had a hard time extricating the title from the Article object. I already knew that all the articles are saved in the class variable all of the Article class. I made a local variable sort inside the method where I would display all the articles that I searched for. Then, I used the sort_by method and saved it into the sort variable. After that I iterated them by using each method to display all the articles with index.

And, here’s the output:

If interested, you can go check my demo video what it looked like before sorting: https://www.youtube.com/watch?v=49u6kwSTNQg&t=10s

--

--