Posted on

The Minimum Viable Tutorial


Since I’ve been talking about Ruby tutorials, I thought I’d write one.

Say you don’t know Ruby, but you’d like to learn. What’s a good starter project?

In my opinion, a good project should have the following characteristics. It should be useful, but it should also be simple; ‘better’ alternatives should be shelved in favor of ‘easier’, in the beginning.

Once you understand the simplest examples, add complexity. Until then, minimize it.

There’s also a frustrating tendency, in a number of books, to walk through a starter project but then diminish it by saying at the very end, ‘this is only a toy project.’ This one, then, is not useless; you can add functionality, but as it stands, without any additions to what is written here, it is useful.

So let’s begin.

I’ll walk you though a system to take user input, print it out, store it to file, sort it, and then print it back out.

The first thing we want to do is take input, from the command line. Open up a file I’ll save as filename with the suffix .rb, and type in this:

puts word

Then run it by typing in ruby filename.rb, at the command line. You should see it print a blank line before returning you to the command line. This is because you entered no arguments.

To run it correctly, then, type ruby filename.rb dog. This time you should see


as shown above.

Now let’s say you wanted to print, in the output, some surrounding text, saying “This is the text you entered.” You could do it by typing by replacing puts word with

puts "You entered #{word} as your text."


line = "You entered " + word + " your text."
puts line

Notice that, in the second example, if you forgot to enter your text, you’ll now get an error saying ‘+ can’t convert nil into String.’

To avoid sending nil, using the second method, you could wrap this in an if-then test. For instance:

unless word.nil?
   line = "You entered " + word + "your text."
   line = "You didn't enter anything."
puts line

Now you have your line. Let’s print to file, in this case, to a file named test.txt. To print it to file, use this command:

yourfile ="test.txt", "w")
yourfile.puts line

To read it from file, open and save a second file, secondfile.rb (or whatever you want), and write this:

line = File.readlines("test.txt")
puts line

Run it by typing ruby secondfile.rb. And there’s your mini-tutorial in Ruby, the very first steps.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s