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
Atom. 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.

Goals

Use a text editor.

Write and save a Ruby program into a file

Start and connect to the RailsBridge virtual machine, if you are using it for the workshop

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:

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.

If you're using the RailsBridge virtual machine, save the file
in the same folder you created the virtual machine. That folder is shared
between your laptop and the vm, like 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, connect to the
VM, and cd to your workspace directory

Type this in the terminal:

ls

Expected result:

my_program.rb

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 exactly 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 your workspace directory.

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.

Explanation

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!