Ruby's syntax is designed to be simple, readable, and beginner-friendly. Let's understand how Ruby reads and executes your program.
Ruby considers the end of a line as the end of a statement. This means you don't need to use semicolons (;
) like you do in some other languages.
# Ruby code that prints "Hello" and "World" on separate lines
puts "Hello"
puts "World"
You can still use semicolons if you want to put multiple statements on a single line:
puts "Hello"; puts "World"
Note: Semicolons aren't commonly used in Ruby code.
Identifiers and Keywords
Identifiers are the names you use for variables, methods, and classes. Ruby has some simple rules:
- Variable and method names start with a lowercase letter or underscore (e.g.,
name
,my_value
). - Class names start with an uppercase letter (e.g.,
Person
,Calculator
). - Ruby is case-sensitive —
value
andValue
are different.
Keywords are reserved words you can't use as names for your variables or methods because they are part of the language syntax.
Some common keywords are:
alias |
and |
begin |
break |
case |
class |
def |
defined? |
do |
else |
elsif |
end |
ensure |
false |
for |
if |
in |
module |
next |
nil |
not |
or |
redo |
rescue |
retry |
return |
self |
super |
then |
true |
undef |
unless |
until |
when |
while |
yield |
Ruby Variables
A variable is like a container that holds data in your Ruby program. The syntax to create a variable is:
variable_name = value
For example,
user_age = 25
Variable names are written in snake_case
.
Note: Ruby is dynamically typed, so you don't need to mention the data type when creating a variable.
To learn more about variables, visit Ruby Variables.
Writing Your Ruby Program
Here's a simple Ruby program that prints a name:
name = "Jack"
puts "My name is #{name}"
Output
My name is Jack
In the above program, we printed a message using the puts
method and the name
variable.
The #{name}
part inside the string is called string interpolation — it lets us insert the value of a variable into the string.
Note: The syntax of string interpolation in Ruby is #{variable_name}
.
More on Ruby Syntax
You've now seen how Ruby's syntax makes code simple and readable — but that's just the beginning.
Ruby has clear, consistent syntax for things like comments, conditional statements, methods, and classes, each with its own structure and purpose. Understanding these will help you write more powerful and organized Ruby programs.
We'll explore these topics gradually, but you're welcome to dive into any of them if you need the syntax for these right now.