Skip to content

Ruby Syntax

Let’s start with a minimal Ruby program. Ruby files conventionally use the .rb extension.

#!/usr/bin/env ruby
# The above line is a 'shebang', common in Unix-like systems to specify the interpreter.
# -w enables warnings, which is good practice during development.
puts "Hello, Ruby!"

To run this, save it as hello.rb and execute from your terminal:

$ ruby hello.rb

This will produce:

Hello, Ruby!

Now, let’s explore some basic syntax concepts:

Whitespace (spaces, tabs) is generally ignored, except within string literals or when it resolves ambiguity. Consistent indentation is crucial for readability but not syntactically required by the interpreter itself (though style guides like RuboCop enforce it).

Ruby interprets semicolons (;) and newline characters as the end of a statement. Semicolons are rarely needed if each statement is on its own line. To continue a statement onto the next line, end the current line with an operator (like +, -) or a backslash (\).

a = 1 + 2 + \
3 # Statement continued with backslash
puts a # Output: 6
b = 10 +
5 # Statement continued because it ends with an operator
puts b # Output: 15

Identifiers are names for variables, constants, methods, classes, and modules. Ruby identifiers are case-sensitive (e.g., name and Name are different). They typically consist of alphanumeric characters and underscores (_).

  • Local variables and method names: snake_case (e.g., user_name, calculate_total).
  • Instance variables: @snake_case (e.g., @user_name).
  • Class variables: @@snake_case (e.g., @@instance_count).
  • Global variables: $snake_case or $kebab-case (e.g., $debug_mode). Use sparingly.
  • Constants: UPPER_SNAKE_CASE (e.g., MAX_USERS, PI).
  • Class and Module names: CamelCase (e.g., UserServic, HttpUtils).

Method names can end with ? (conventionally for methods returning a boolean, e.g., empty?) or ! (conventionally for methods that modify their receiver or have a more dangerous/surprising effect, e.g., sort!).

These words have special meaning in Ruby and cannot be used as variable or constant names. They can, however, sometimes be used as method names.

Keywords Group 1Keywords Group 2Keywords Group 3Keywords Group 4
BEGINENDaliasand
beginbreakcaseclass
defdefined?doelse
elsifendensurefalse
forifinmodule
nextnilnotor
redorescueretryreturn
selfsuperthentrue
undefunlessuntilwhen
whileyield__FILE____LINE__
__ENCODING__

This list is representative. For the authoritative list, consult the official Ruby documentation.

Heredocs are a convenient way to create multi-line strings. They start with << followed by a delimiter. The string ends when the delimiter appears again on a line by itself.

Standard Heredoc (<<DELIMITER): Interpolation and escape sequences are processed.

name = "World"
standard_heredoc = <<MESSAGE
Hello, #{name}!
This is a multi-line string.
Indentation is preserved.
MESSAGE
puts standard_heredoc

Non-interpolating Heredoc (<<'DELIMITER'): No interpolation or escape sequences.

non_interpolating_heredoc = <<'TEXT'
This will print literally: #{name}\n.
TEXT
puts non_interpolating_heredoc

Squiggly Heredoc (<<~DELIMITER): This is very useful. It allows you to indent the heredoc content in your source code for readability, and it automatically removes the leading whitespace from each line up to the level of the least indented line or the closing delimiter.

def get_message
user = "Alice"
squiggly_heredoc = <<~GREETING
Hello, #{user}.
Welcome to our application!
We hope you enjoy your stay.
GREETING
# The 'We hope' line will have 2 spaces of indentation, GREETING will have 0.
end
puts get_message

Heredoc for command execution (<<DELIMITER“): The content is executed as a shell command.

command_output = <<`CMD`
echo Listing files:
ls -lah
CMD
puts command_output

The closing delimiter must be at the beginning of its line, optionally followed by a semicolon. There should be no space between << (or <<~, <<-) and the delimiter.

Ruby allows you to define blocks of code that execute at specific times:

  • BEGIN { code }: The code within a BEGIN block is executed once before any other code in the script runs.
  • END { code }: The code within an END block is executed just before the program terminates, after all other code has run (including during exception handling).
#!/usr/bin/ruby
puts "This is the main Ruby Program."
BEGIN {
puts "Initializing Ruby Program... (BEGIN block)"
}
END {
puts "Terminating Ruby Program... (END block)"
}

Output:

Initializing Ruby Program... (BEGIN block)
This is the main Ruby Program.
Terminating Ruby Program... (END block)

BEGIN and END blocks are less common in modern application code but can be useful for setup/teardown in scripts or specific library scenarios.

Comments are ignored by the Ruby interpreter and are used to explain code.

  • Single-line comments: Start with a # (hash) character and extend to the end of the line.
  • Multi-line (block) comments: Start with =begin on a line by itself and end with =end on a line by itself. Everything between these two markers is a comment. These must be at the very beginning of their respective lines.
# This is a single-line comment.
x = 10 # This comment is after a statement.
=begin
This is a multi-line comment.
It can span several lines.
Useful for temporarily disabling large blocks of code.
=end
puts "Code after multi-line comment."

Understanding these fundamental syntax rules is the first step to writing effective Ruby programs.