Expand All

Running Programs From A File

irb isn't a good tool for writing long programs. Code is entered one line at a time. You can't save your work, and you can't share it when you're done.

Instead, we write code in a file and run it from the command line.

For writing code, we use a program called a text editor.

A text editor is a word processor that saves in plain text format. This is unlike Word, which saves files in a special format that only Word can read.

We may have recommended a particular text editor during the Installfest, such as SublimeText. You can use any editor you like so long as it saves plain text.

It'll helpful to keep your text editor running, since you'll be coming back to it often.


  • Use a text editor.

  • Write and save a Ruby program into a file

  • Start and connect to the RailsBridge virtual machine

  • Run Ruby code saved in a file

Step 1

Start your text editor.

In your text editor, create a new file called my_program.rb

Type this in the file my_program.rb:
# This is a comment line.
# Comment lines start with a pound sign, and the computer ignores them.
# Since the computer ignores them you can use them for notes to yourself.
puts 'This code is in a file!'
some_variable = 19
puts "I stored a variable with the value #{some_variable}!"

Step 2

Save the file.

Save the file in railsbridge in your desktop - the folder shared with your virtual machine. Any files your put there show up in /vagrant on the VM, and vice versa, like Dropbox or Google Drive.

Did you notice we added .rb at the end of the name? It's standard practice to name Ruby files this way, to help people and tools recognize the file contains Ruby code.

When you saved the file, your text editor may have added colors to the code. It recognizes the file contains Ruby, and will mark up different kinds of words with different colors. This is called "syntax highlighting", which makes it easier to read code.

Step 3

Let's look at the file.

Open your terminal, and connect to the VM

Type this in the terminal:

Expected result:

Type this in the terminal:

more my_program.rb
Expected result:
puts 'This code is in a file!'
some_variable = 19
puts "I stored a variable with the value #{some_variable}!"

my_program.rb was saved in plain text - you see exactlty what you typed. If this were a Word document, you would see a screenful of weird characters and formatting, and you would get errors when you ran it.

Step 4

Now run the code. Stay in /vagrant on the Virtual Machine.

Type this in the terminal:

ruby my_program.rb
Expected result:
This code is in a file!
I stored a variable with the value 19!

If you didn't see this message, troubleshoot with a TA. We will do this for the rest of the tutorial, so it's important to ensure everything works.


Congratulations! You've run your first Ruby program!

Ruby programs are written in files and run from the command line. As your program becomes larger and larger, it may span many files!

Next Step: