How to build a simple terminal application

Chau Anh
3 min readNov 12, 2017
Picture Source: complex.com

Last week I learned how to create terminal applications using Ruby.

One of the applications I was taught to build was an app that displays posts from a given subreddit (for example, /r/programming) and the comments for a given post, which is specified by the user.

To make a connection request to reddit, we use a useful package called ‘unirest’. Unirest helps simplify requests to and responses from the web.

To begin, install unirest

gem install unirest

Once unirest is installed, begin your code by requiring unirest

require 'unirest'

Then, think of a subreddit you would like the app to parse and start creating a request in Ruby as follows

response = Unirest.get("https://www.reddit.com/r/programing/.json")
posts = response.body["data"]["children"]

A few notes on these two lines of code:

  1. Any page on Reddit can be viewed in .json format by adding the .json modifier at the end of the url.
  2. response.body is a built-in function in unirest that parses and returns the body of a webpage
  3. Think of any given reddit page as a Giant Hash and all its contents (posts, score, author, etc.) are stored within hashes within this hash. Therefore, after a close look at r/minimalism/.json, you will see that the posts we are looking to display using our app are stored in an array [“children”], which is stored in a hash [“data”], which is stored in the Giant Hash #{response.body}.
data structure within a subreddit

The next step is to write the codes that display the posts which we just located. This can be accomplished using a loop. Any type of loop will do. I used the times loop because it is the most intuitive method for me.

index = 0
posts.length.times do
post = posts[index]
puts "#{index}. #{post["data"]["title"]}"
index = index + 1
end

A few notes on this loop:

  1. As you recall from above, ‘posts’ is an array containing all the posts we wish to display in our terminal. post[index] naturally returns the specific post within the posts as index increments from 0 to n.
  2. #{index} is just a quick trick that assigns a number order to each post that is iterated. This makes our data looks neat, but by no means is necessary.
  3. post[“data”][“tittle”] gives us the title of each post within the subreddit. The logic works similarly to the Giant Hash example demonstrated earlier.

The second part of this exercise is to allow the users the ability to choose a post and print out the comments for that post.

Walk through of the second part is TBD. In the meantime, happy coding!

Thanks for reading.

--

--