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.
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 nilWhy 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.
- Ruby reads one statement per line
- Double quotes: run #{...} and escapes
- puts or p turns the value into text
- The terminal shows the text
Single quotes skip step two and keep every character literally.
General pattern: output and strings
puts "text"
puts "text with #{expression}"
puts('first', 'second')
variable = "value" # a comment
p variableputs 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.
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
- Parentheses are optional
puts("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.
- print adds nothing
print "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.
- p shows the inspect form
p "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.
- nil with puts and with p
puts nilputs 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.
- Interpolation in double quotes
puts "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.
- Single quotes are literal
puts '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.
- Any expression inside braces
puts "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.
Hello, World
This also works
no newline here
"text"
42
nil
I am learning Ruby.
Single quotes: #{language}
2 + 3 = 5puts, 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.
| Method | Output style | Returns |
|---|---|---|
| puts | Human-readable text, one item per line, adds a newline | nil |
| The same text as puts, but no newline is added | nil | |
| p | The inspect form: strings keep quotes and nil shows as nil | Its argument |
| pp | Like p, but wraps wide nested data over several lines | Its argument |
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 nilIn 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.
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 commentThe 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.
| Example | Parentheses advice |
|---|---|
| puts "Hi" | Leave them out: a plain statement reads well without them |
| total = add(1, 2) * 3 | Keep them: the call is inside a larger expression |
| "ruby".upcase | None to write: a call without arguments needs no parentheses |
| puts(1 + 2) * 3 | A 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
# 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 quotesExpected: 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
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
Quick quiz 2 / 3
Quick quiz 3 / 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