Thuta Learning
Ruby
BasicProgrammingBeginner

Syntax & Hello World

RubyLesson 420 min

What you'll walk away with

  • Write and run a Hello World program and explain that a newline, not a semicolon, ends a statement
  • Choose between puts, print, p and pp for the output you need
  • Interpolate values with #{...} in double-quoted strings and explain why single quotes print it literally
  • Explain when parentheses on a method call are optional and when leaving them out causes trouble

Explain it simply

Ruby syntax in plain words

Ruby's syntax is designed to stay out of your way. A line ends where you press Enter, so no semicolon is needed, and calling a method such as puts usually needs no parentheses. Text goes between quotes, and double quotes can carry values inside them: "Hello, #{name}". Four short commands, puts, print, p and pp, send results to the terminal, each in a slightly different style. Learn the differences now and reading Ruby output, yours or other people's, becomes much easier.

Problem → Why → Solution

The problem: even a first program prints wrongly or crashes

Most people new to Ruby meet one of these surprises on day one. In the first, you expect "I am learning Ruby." but the text #{language} appears unchanged; there is no error, so the mistake hides silently, which makes it the worst of the three. In the second, you assume "Lessons done: " + count will join text and a number as it does in JavaScript, but a TypeError appears. In the third, you expect 9 from puts(1 + 2) * 3, but 3 is printed and a NoMethodError follows.

In none of the three is Ruby wrong; the code does not mean what you meant. This lesson explains that the kind of quote changes the meaning, that + will not mix text and numbers for you, and that parentheses decide where a method call ends.

surprises.rb
language = "Ruby"
count = 3
puts 'I am learning #{language}.'    # prints #{language} literally
puts "Lessons done: " + count         # TypeError
puts(1 + 2) * 3                       # NoMethodError: undefined method '*' for nil

Why Ruby behaves like this

Ruby follows simple rules strictly: nothing is evaluated inside single quotes, String#+ accepts only a String, and whatever follows the closing parenthesis of puts(...) works on the value that puts returned. Once the rules are visible, the errors make sense.

Core concept: statements, method calls and quotes

A Ruby program is a list of statements, and a statement normally ends where the line ends. There is no semicolon to type and no main function to write; Ruby starts at the first line of the file. If an expression is clearly unfinished, for example a line that ends with + or a comma, Ruby simply keeps reading onto the next line. A # starts a comment that runs to the end of the line, and Ruby ignores it completely.

Printing is done by ordinary methods, not by special syntax. puts, print, p and pp are methods available everywhere in a program, so puts "Hello" is a method call written without parentheses, exactly the same as puts("Hello"). Ruby lets you leave the parentheses out when the call is a simple statement, and most Ruby code does, but you should keep them when the call sits inside a larger expression or is chained with another call. The quick rule is: if leaving them out makes you stop and wonder how Ruby will group the line, add them.

Strings come in two quote styles with different powers. Double quotes understand escapes such as \n for a new line and \t for a tab, and they evaluate #{...} interpolation: Ruby runs the code between the braces, converts the result to text with to_s and pastes it in. Single quotes are literal: apart from \' and \\ nothing is processed, so 'Hi #{name}' prints the braces exactly as written. Interpolation also saves you from a common error, because "Total: " + 5 raises a TypeError, since Ruby will not silently turn the number 5 into text, while "Total: #{5}" just works.

puts and p differ in purpose. puts prints the text a person should read; p prints the inspect form, with quotes around strings and nil written out, which is what you want while debugging.

Mental model: write a call, Ruby evaluates, text appears
  1. Ruby reads one statement per line
  2. Double quotes: run #{...} and escapes
  3. puts or p turns the value into text
  4. The terminal shows the text

Single quotes skip step two and keep every character literally.

General pattern: output and strings

ruby
puts "text"
puts "text with #{expression}"
puts('first', 'second')
variable = "value"   # a comment
p variable

puts can be called with or without parentheses, and several arguments are separated by commas. Code inside #{...} in double quotes is evaluated. After a #, the rest of the line is a comment. p shows a value in its inspect form.

Example: several kinds of output and two quote styles

Each line of this program shows one output command. Predict the printed lines before you run it, and watch in particular the empty line from puts nil and the single-quoted string.

hello.rb
puts "Hello, World"
puts("This also works")
print "no newline here"
print "\n"
p "text"
p 42
puts nil
p nil
language = "Ruby"
puts "I am learning #{language}."
puts 'Single quotes: #{language}'
puts "2 + 3 = #{2 + 3}"

Code breakdown

  1. Parentheses are optionalputs("This also works")

    This line behaves exactly like the first one. The parenthesised form makes it obvious where the argument ends, which helps in more complicated expressions.

  2. print adds nothingprint "no newline here"

    print does not add the newline that puts adds at the end. That is why the next line, print "\n", ends the line by hand.

  3. p shows the inspect formp "text"

    p shows a String with its quotes ("text"), while the number 42 looks the same either way. That makes it useful for telling what kind of value you hold.

  4. nil with puts and with pputs nil

    puts nil prints one empty line, which is the blank line after p 42. p nil writes out the word nil. Seeing nothing fits puts being meant for human readers.

  5. Interpolation in double quotesputs "I am learning #{language}."

    Ruby replaces #{language} with the value of the language variable, giving Ruby. Method calls and calculations also fit between the braces, not only variables.

  6. Single quotes are literalputs 'Single quotes: #{language}'

    Nothing is interpolated inside single quotes, so #{language} appears exactly as typed. Ruby treats this as correct and prints no error, which is why it deserves extra attention.

  7. Any expression inside bracesputs "2 + 3 = #{2 + 3}"

    The 2 + 3 inside the braces is worked out first, 5 becomes text, and it is placed into the surrounding string. You never need to call to_s yourself for this.

You should see
Hello, World
This also works
no newline here
"text"
42

nil
I am learning Ruby.
Single quotes: #{language}
2 + 3 = 5

puts, print, p and pp side by side

All four methods send a value to the terminal, but they differ in how they turn it into text and in what they return. The return value matters because the result of p can be stored in a variable and used, while the result of puts is always nil.

MethodOutput styleReturns
putsHuman-readable text, one item per line, adds a newlinenil
printThe same text as puts, but no newline is addednil
pThe inspect form: strings keep quotes and nil shows as nilIts argument
ppLike p, but wraps wide nested data over several linesIts argument
output_styles.rb
items = ["tea", nil, 3]

puts items           # one element per line, nil becomes an empty line
print items, "\n"    # the list as one line, no newline of its own
p items              # inspect form, quotes and nil visible
pp items             # same as p for small data

result = p("kept")   # p prints, then returns its argument
puts result
shown = puts("shown")
p shown              # puts always returns nil

In Ruby 4.0.9 this code prints tea, an empty line, 3, then ["tea", nil, 3] three times, "kept", kept, shown and finally nil, in that order. Notice that puts unpacks the array and shows each element on its own line.

Quotes, escapes and comments

A backslash inside double quotes creates special characters: \n is a new line, \t is a tab and \" is a quote mark inside the string. In single quotes only \' and \\ work. A # comment runs to the end of the line, so it can also sit after code.

quotes.rb
puts "Tab:\tend"      # double quotes turn \t into a real tab
puts 'Tab:\tend'      # single quotes keep the backslash and the t
puts "She said \"hi\""
puts 'It\'s fine'
puts "Total: #{3 * 4}"
puts "Done" # a trailing comment

The first line prints Tab:, a real tab and end, while the second prints Tab:\tend exactly as written. The remaining lines print She said "hi", It's fine, Total: 12 and Done.

Where a statement ends and when to keep parentheses

Ruby ends a statement at a newline unless the expression is clearly unfinished, such as a line that ends with an operator or a comma. A semicolon can separate two statements on one line, but style guides discourage it. For parentheses, a simple rule of thumb works well.

ExampleParentheses advice
puts "Hi"Leave them out: a plain statement reads well without them
total = add(1, 2) * 3Keep them: the call is inside a larger expression
"ruby".upcaseNone to write: a call without arguments needs no parentheses
puts(1 + 2) * 3A trap: the parentheses end the call, so * 3 is applied to the nil that puts returned

In real projects

Output and style in real projects

In real scripts, puts is the workhorse for output a person reads: progress messages, reports, the result of a command-line tool. p is what developers type while debugging, because it shows the exact value including quotes and nil, and pp is the choice for nested data such as the hash a JSON library returns. Larger applications replace puts with a logger that adds timestamps and levels, but the habit of choosing the output form that fits the reader carries over.

Two conventions appear in almost every Ruby file: a magic comment, # frozen_string_literal: true, on the first line (explained in the Variables and Data Types lessons), and a consistent quote style. Many teams enforce style with RuboCop, whose default prefers single quotes for strings without interpolation or escapes and uses double quotes only when you need them.

Common mistakes

Common beginner mistakes

1. Interpolating inside single quotes

puts 'I am learning #{language}' raises no error and prints #{language} as plain text. Switch to double quotes to get the value. Whenever #{ shows up in the output, check the quote style first.

2. Joining a string and a number with +

"Lessons done: " + 3 raises a TypeError (no implicit conversion of Integer into String). Write "Lessons done: #{3}" or convert with 3.to_s yourself. Interpolation needs no conversion at all and is shorter and easier to read.

3. Continuing after puts(...)

puts(1 + 2) * 3 prints 3 and then raises NoMethodError: undefined method '*' for nil, because the parentheses close the puts call and * 3 is applied to the nil that puts returned. Put the whole expression inside: puts((1 + 2) * 3).

Best practices

Best practices

  • Choose puts for human readers, p while debugging and pp for large nested data.
  • Keep one quote style across a project: single quotes for strings without interpolation, double quotes where you need them.
  • When a call without parentheses leaves any doubt about what the line means, add them; one pair of parentheses saves the reader some thinking.

Mini challenge

Mini challenge: a receipt printer

Store a customer, an item, a quantity and a unit price in variables, then print a four-line receipt using puts, print and p.

  • Write four variables: customer = "Aye", item = "Tea", quantity = 3, unit_price = 1500
  • Print "Receipt for Aye" using puts and double-quoted interpolation
  • Print "Tea x 3 = 4500 MMK" on the second line, calculating quantity * unit_price inside #{...}
  • Use print twice to produce "Paid: yes" on one line, then use p to show "Thank you" with its quotes
receipt.rb
# receipt.rb
# TODO: store the customer, item, quantity and unit price in variables

# TODO: puts the first line, "Receipt for ..." (interpolate the customer)
# TODO: puts the second line, "Tea x 3 = 4500 MMK" (calculate the total inside #{})
# TODO: print "Paid: " and then "yes" plus a newline (two print calls)
# TODO: use p to show "Thank you" with its quotes

Expected: The program prints these four lines: Receipt for Aye Tea x 3 = 4500 MMK Paid: yes "Thank you"

Show hint

Writing print "yes\n" ends the line, because \n works inside double quotes. To show text side by side on one line, two print calls fit better than puts. p "Thank you" shows the quotes without you typing them into the text.

Show solution
receipt.rb
customer = "Aye"
item = "Tea"
quantity = 3
unit_price = 1500

puts "Receipt for #{customer}"
puts "#{item} x #{quantity} = #{quantity * unit_price} MMK"
print "Paid: "
print "yes\n"
p "Thank you"

Quick quiz 1 / 3

With name = "Aye", what does puts 'Hi #{name}' print?

Quick quiz 2 / 3

After x = puts("hi"), what does p x print?

Quick quiz 3 / 3

What happens with puts "Count: " + 3?

What to remember

  • A statement ends at the end of the line; no semicolon or main function is needed, and # starts a comment
  • puts is for readers, print adds no newline, p shows the inspect form and pp suits nested data; puts returns nil while p returns its argument
  • #{...} interpolation works only inside double quotes; single quotes print the text literally
  • Parentheses end a method call, so puts(1 + 2) * 3 applies * to nil

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Syntax & Hello World | Thuta Learning