Create a Console Application in Ruby

Become a Subscriber

I love to teach developers how to program with Ruby. I think what has made me a great programmer was my early days of learning console and creating text-based games. Most tutorials and teaching tools have you jump into building a website, but that requires understanding networking, installing software, often using a framework, etc. The layers of understanding get complex quick, convoluting the actual process of writing a program. On the other hand, most operating systems already have Ruby installed and you can build an app with little to no-setup. Let’s do it!

Start by checking for Ruby. Open terminal/console/whatever command line tool you have installed on your computer. Terminal and Console are the most common and a search from your start bar or spotlight (depending on OS) will usually reveal one of them. If you are staring at a program with one of these names, some text.. and a cursor waiting for input, you’re in good shape to start entering some commands. First let’s check for ruby:

ruby -v

Type that in and hit enter. Did you get a response? If the response was something along the lines of ruby x.x.x then you are good to go. If not, go search the web and learn how to install Ruby for your OS.

Now we need to create our first program. I recommend starting with codecademy to learn Ruby syntax. If you want to get right to it, that is fine too! Just use any text editor (notepad, vim and nano are present on almost all machines). I’m going to teach you how to use vim if you want to follow instructions to the letter:

First we will start a new file in vim:

vi test.rb

Now hit the a key to add text to the file, and type/paste the following:

class App 
  def self.hello
    puts "hello to you too"
  end 
end

loop do
  input = gets.chomp
  command, *params = input.split /\s/
  case command
    when 'hello'
      puts App.hello
    else
      puts 'Invalid command'
  end 
end

If that’s pasted in, you can hit the escape key and type :x to save and close the file. Congrats, you have created a console application! Before we run it, lets talk about the code.

Creating a Ruby Class

The App class is going to contain methods that we can call by typing a command in the console, and sending a mapped response. The loop keeps an open dialog with the command line to listen for user input. The command is the pans (gets.chomp) and we use a switch statement to match text input. If the user enters hello the application will respond with the App.hello command which puts the text “hello to you too” back out to the console. Let’s run it and see:

ruby test.rb

Now enter the text hello and see if your program responds. Good luck, and happy programming!