Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 134 ยท Getting Started

Your First Ruby Program

Write and run your first Ruby script. Learn puts, print and p, comments, how the interpreter reads a file and how to read syntax errors, with live examples.

The traditional first program prints a greeting. In Ruby it is a single line, with no main function, no class and no imports. A Ruby file is simply a list of instructions that the interpreter runs from top to bottom. That makes Ruby one of the quickest languages to start with, and it also means everything you learn here about printing, comments and reading error messages will be used in every later lesson.

In this lesson you will print text three different ways (and learn why there are three), write comments, see how the interpreter treats your file, and practice reading the three kinds of failures you will meet most often: syntax errors, name errors and type errors.

Hello, world

Ruby Hello, world

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

puts (say "put string") is a method that writes its argument to the screen followed by a newline. The text in quotes is a string. No parentheses are needed, though puts("Hello, world!") is identical. In the Ruby community, parentheses are usually left out for simple calls with one or two arguments, such as puts and require, and kept for calls where they make the meaning clearer.

If you save that line in a file called hello.rb and type ruby hello.rb in a terminal, you get the same output. On this site the Run button does the same thing: it saves your code as main.rb and runs ruby main.rb.

puts, print and p

Ruby has three everyday printing methods, and they differ in important ways.

Ruby Three ways to print

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

  • puts prints the friendly text form of each argument (to_s) and ends with a newline. If you pass an array, it prints each element on its own line, flattening nested arrays. puts nil prints an empty line.
  • print prints the same friendly form but adds nothing: you control the line breaks yourself with "\n".
  • p prints the inspected form (inspect), the way you would write the value in code: strings keep their quotes, nil appears as nil and arrays show their brackets. It is the best tool for debugging.

Compare the lines puts nil (an empty line) and p nil (the word nil). When you wonder what a value really is, use p. When you want output for a human, use puts.

p has one more useful property: it returns its argument, so you can insert it into the middle of an expression without changing the program.

Ruby p returns what it prints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

p(3 + 4) prints 7 and evaluates to 7, so total becomes 14. puts always returns nil (the second p shows it). A bare p with no arguments prints nothing. A p with several arguments prints each on its own line, and then returns them as an array.

When debugging, write p value rather than puts value. The quotes tell you whether you have the string "5" or the number 5, and nil is visible instead of being an invisible empty line.

Comments

A comment is text the interpreter ignores. In Ruby a comment starts with # and runs to the end of the line.

Ruby Comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Use comments to explain why code does something unexpected, not to repeat what the code says. # add one to count above count += 1 is noise. # the API counts from 1, we count from 0 is useful.

Two special comments appear at the top of many real files. A shebang (#!/usr/bin/env ruby) lets a Unix system run the file directly, and the magic comment # frozen_string_literal: true changes how string literals behave. The second one is explained in Strings.

Ruby
#!/usr/bin/env ruby
# frozen_string_literal: true

# read-only example: a typical file header
puts "A script that can be run as ./greet.rb after chmod +x"

Several lines, several statements

Each line is normally one statement, with no terminating semicolon. A line can continue onto the next one when it clearly is not finished: it ends with an operator, a comma, or an open parenthesis.

Ruby Statements and line continuation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

When a line ends with +, the interpreter knows the expression is incomplete and reads on. Putting the operator at the end of the line is important: a line that begins with + 3 would be a new statement, not a continuation.

How the interpreter reads your file

When you run ruby main.rb, the interpreter does three things:

  1. Parses the whole file. Since Ruby 3.4 the parser is called Prism. If the code is not valid Ruby, you get a SyntaxError and nothing runs at all.
  2. Compiles the code into instructions for the Ruby virtual machine.
  3. Executes the instructions from the first line to the last, top to bottom.

Because step 1 happens for the entire file first, a typo on line 10 prevents line 1 from running, as the next example shows. Everything in the file that is not inside a method or class definition runs immediately, which is why a simple script needs no main.

A few helpers are always available to find out where you are:

Ruby Where am I running

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

ARGV holds the words typed after the script name in the terminal. You will use it in Scripting and Command-Line Tools.

Reading your first errors

Everybody makes mistakes. What matters is reading the message. Ruby reports problems in three main ways.

Syntax errors

A SyntaxError means the code is not valid Ruby. Here a quote is missing:

Ruby A missing quote (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Nothing prints, not even start. The message says unterminated string meets end of file and ends with main.rb:3: syntax errors found (SyntaxError), followed by a copy of your code with ^~~ markers under the places Prism found confusing. Prism often lists several complaints for one real mistake, because one missing quote throws off everything after it. Fix the first one and run again. The most common syntax errors are a missing end, a missing quote and a missing bracket.

Name errors

Ruby A misspelled name (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You get main.rb:2:in '<main>': undefined local variable or method 'greting' for main (NameError), plus a Did you mean? greeting hint. Ruby does not know the name greting (a typo for greeting), so it complains. The words "for main" refer to main, the object at the top level of every script. The same exception appears for an unknown constant: puts Hello fails with uninitialized constant Hello (NameError).

Type errors

Ruby Mixing a string and a number (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby prints main.rb:2:in 'String#+': no implicit conversion of Integer into String (TypeError). A line starting with from main.rb:2:in '<main>' follows: this is the backtrace, the chain of calls that led to the error, with the most recent call first. The fix is to convert explicitly with age.to_s, or to interpolate:

Ruby Fixing it with interpolation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Interpolation (#{...}) works only inside double-quoted strings. Single-quoted strings print the text literally; Strings covers the difference in detail.

Good habits from day one

  • Use two spaces for indentation. This is the universal Ruby convention.
  • Name files and variables in snake_case: first_name, bank_account.rb.
  • Put one idea per line, and keep lines under about 100 characters.
  • Run your script often. Small changes and quick runs make errors easy to find.
  • Read the first line of an error message and the line number carefully before changing anything.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does puts nil print?

    puts uses to_s, and nil.to_s is an empty string, so puts prints just a newline. p nil would print the word nil.
  2. 2. Which method prints the inspected form of a value and also returns that value?

    p calls inspect on each argument, prints it and returns the argument (or an array of the arguments), which is why it is handy in the middle of an expression.
  3. 3. A script has a syntax error on its last line. What happens when you run it?

    Ruby parses the entire file before executing anything. A SyntaxError means no line of the script has run.
  4. 4. How do you start a single-line comment in Ruby?

    A # starts a comment that ends at the end of the line. Inside a string literal a # is just a character.

Summary

  • A Ruby file is a list of statements run from top to bottom; no main is needed.
  • puts prints friendly text plus a newline, print prints without one, and p prints the inspected value and returns it.
  • Comments start with #; explain why, not what.
  • Ruby parses the whole file first: a SyntaxError means nothing runs.
  • NameError means an unknown variable, method or constant; TypeError means incompatible types, such as "a" + 1.
  • Read the first line of the message and the file and line number; the backtrace shows the call chain.

Next: How Ruby Runs