Ruby Syntax
Ruby's syntax is designed to stay out of your way. There are no semicolons at the end of lines, no braces required around if bodies, and parentheses are often optional. This lesson covers the ground rules you need before writing real programs.
Statements and lines
Each line is normally one statement. Ruby knows a statement has ended when the line ends — no semicolon needed:
city = "Lisbon"
population = 545_000
puts city
puts populationLisbon
545000
The underscore in 545_000 is just a visual separator; Ruby ignores it.
You can put several statements on one line with ;, but it is rarely done:
a = 1; b = 2; puts a + bIf a line ends with an operator, a comma or an opening bracket, Ruby knows the statement continues on the next line:
total = 10 +
20 +
30
colors = [
"red",
"green",
]
puts total
puts colors.length60
2
Blocks of code use end
Ruby does not use indentation or curly braces to group statements in if, while, def and class. Instead, the block is closed with the keyword end:
temperature = 31
if temperature > 30
puts "Hot day"
puts "Drink water"
end
def square(n)
n * n
end
puts square(9)Hot day
Drink water
81
Indentation is not required by the interpreter, but the community standard is two spaces per level. Always indent — it makes the structure obvious.
Parentheses are optional
When calling a method, parentheses around the arguments can usually be left out:
puts("with parentheses")
puts "without parentheses"
puts [3, 1, 2].max
puts "a-b-c".split("-").inspectwith parentheses
without parentheses
3
["a", "b", "c"]
The usual style: leave them off for simple statements like puts, keep them when you chain calls or pass several arguments, and always keep them when leaving them off would be confusing.
Expressions everywhere
In Ruby almost everything is an expression that returns a value — even if. That allows compact code:
score = 72
result = if score >= 50 then "pass" else "fail" end
puts result
label = score > 90 ? "excellent" : "fine"
puts labelpass
fine
Naming conventions
Ruby uses the first character of a name to tell what kind of thing it is, so following the conventions matters:
| Kind | Convention | Example |
|---|---|---|
| Local variable, method | snake_case |
total_price, send_email |
| Constant | SCREAMING_SNAKE_CASE (starts with a capital) |
MAX_USERS |
| Class, module | CamelCase |
ShoppingCart |
| Instance variable | starts with @ |
@name |
| Global variable | starts with $ |
$stdout |
| Predicate method | ends with ? |
empty? |
| "Dangerous" method | ends with ! |
sort! (changes the object) |
Ruby is case-sensitive: name, Name and NAME are three different things — and Name is a constant, not a variable.
Reserved words
Some words are part of the language and cannot be used as variable names: def, end, if, elsif, else, unless, while, until, for, do, class, module, return, true, false, nil, self, yield, begin, rescue, ensure, and, or, not, case, when, in, then, break, next, redo, retry, super, alias, defined?, undef, __method__.
Tip: Run
ruby -wc file.rbin a terminal to check a file's syntax with warnings, without running it.
Test yourself
How is the body of an if or def closed in Ruby?
- With a closing
} - By un-indenting
- With the keyword
end - With a semicolon
What is MaxSize in Ruby, judging by its name?
- A local variable
- A constant
- An instance variable
- A global variable
What is the community-standard indentation for Ruby code?
- One tab
- Four spaces
- Two spaces
- None