Building My First Ruby Application

Michael Stephens
3 min readJan 11, 2021

The thought of writing a program from scratch was very overwhelming and if I’m being honest, I wasn’t sure if I was ready to do it. After all, I’ve only been working with Ruby for a few weeks and this is my first deep dive into programming but I knew building something from scratch was the next step in my learning evolution and it was something I had to do if I want to continue improving my programming skills.
One of my favorite activities prior to the pandemic was going out with friends to local restaurants and playing trivia so I thought it would fun to build a trivia game. I found a trivia API to source the data for the trivia questions and went about conceptualizing how the user would interact with the game.
I knew I wanted to allow the user to customize their game by allowing them to choose from different categories of questions, this presented me with my first real challenge of the project. When you visit the website that hosts the API you have the option of choosing questions from a single category or choosing a category with questions from multiple categories. Unfortunately, the API has 24 categories and limits the maximum number of questions to 100. Because the API randoms assigns the questions every time it is called there was no way to achieve the gameplay I wanted using a static URL to the API. I notice that the API used a predictable naming pattern for their URL and so decided to structure my application to take inputs from the user and inject those inputs into the URL.

In the URL above you that there is a amount=10 and category=9, those two values represent the number of questions and the category of the question. The first thing I had to do was two set up a default value so I could make the intial call to the API to get the available categories. I then created a method that used gets.strip to get the users in put and saved in variable called category

That information was then passed into another method as an arguement which I used to create a new instance of the API class where it was stored in a hash called options:. This was stored as hash because it was taking two pieces of information from the user.

Then used method called encode_www_form to take the values in the hash which reformats the data into the format of the API’s URL.

The next step was to do a new API call using the modified URL which gave the questions from the category selected by the user. From the point all I had to do was use JSON to parse through the new data, iterate through that data get the question, correct_answer, and incorrect_answers and store them in a new array.

And that is how I was able to solve the single biggest challenge of my first attempt at building an application from scratch.

--

--