Ruby Syntax Basics
Prerequisites: How Ruby code runs
A few rules cover most of what Ruby code looks like.
One statement per line. No semicolons are needed at the end of a
line. (You can put two statements on one line separated by ;, but
it's rarely done.)
puts "one"
puts "two"
Blocks of code end with end. Where other languages use curly
braces, Ruby uses keywords:
if 10 > 5
puts "Ten is bigger"
end
Ten is bigger
Indentation is two spaces. Unlike Python, Ruby doesn't require
indentation — end marks where a block stops — but every Ruby project
indents with two spaces, so code stays readable.
Case matters. name and Name are different: names starting with
a lowercase letter are variables and methods; names starting with a
capital letter are constants and classes.
Method calls can drop parentheses. puts("hi") and puts "hi" are
the same. The convention: leave them off for simple statements like
puts, and include them when a call is part of a bigger expression.
Everything returns a value. Even if produces a value, which is
why irb always shows a => result.
Common mistakes
- Forgetting an
end. Ruby reportssyntax error, unexpected end-of-input— count yourif/def/doopeners against yourends. - Putting a space between a method name and its opening parenthesis,
as in
puts ("a", "b"). Ruby reads the space as the start of a single argument and fails. Writeputs("a", "b")orputs "a", "b".