Ruby Syntax: A Complete Quick-Reference Guide
By RubyLearning
This Ruby syntax cheat sheet covers every fundamental construct you need for day-to-day Ruby programming. Bookmark it as your go-to Ruby syntax reference and return whenever you need a quick reminder of Ruby basic syntax rules.
Variables
Ruby uses naming prefixes to distinguish variable scope. No type declarations are needed.
name = "Alice" # local variable
@name = "Alice" # instance variable
@@count = 0 # class variable
$verbose = true # global variable
MAX_SIZE = 100 # constant Data Types
Everything in Ruby is an object, including numbers and booleans.
"hello" # String
42 # Integer
3.14 # Float
:status # Symbol (immutable, lightweight identifier)
true # TrueClass (Boolean)
false # FalseClass (Boolean)
nil # NilClass (absence of value)
[1, 2, 3] # Array
{ a: 1 } # Hash Operators
Standard arithmetic, comparison, logical, and assignment operators.
# Arithmetic
2 + 3 #=> 5
10 - 4 #=> 6
3 * 7 #=> 21
10 / 3 #=> 3 (integer division)
10 % 3 #=> 1
2 ** 8 #=> 256
# Comparison
5 == 5 #=> true
5 != 3 #=> true
5 > 3 #=> true
5 <= 5 #=> true
1 <=> 2 #=> -1 (spaceship operator)
"a" === "a" #=> true
# Logical
true && false #=> false
true || false #=> true
!true #=> false
# Assignment
x = 10
x += 5 # x is now 15
x -= 2 # x is now 13
x *= 3 # x is now 39
x /= 3 # x is now 13
x ||= 7 # assigns 7 only if x is nil or false String Interpolation and Common Operations
Double-quoted strings support interpolation and escape sequences. Single-quoted strings are literal.
name = "Ruby"
# Interpolation (double quotes only)
"Hello, #{name}!" #=> "Hello, Ruby!"
'Hello, #{name}!' #=> "Hello, \#{name}!"
# Common string methods
"hello".upcase #=> "HELLO"
"HELLO".downcase #=> "hello"
"hello".capitalize #=> "Hello"
"hello".length #=> 5
"hello world".split #=> ["hello", "world"]
"hello".include?("ell") #=> true
"hello".gsub("l", "r") #=> "herro"
"hello" + " world" #=> "hello world"
"ha" * 3 #=> "hahaha"
" hello ".strip #=> "hello"
"hello".freeze # makes string immutable Conditionals
Ruby provides several conditional constructs. Only false and nil are falsy; everything else is truthy.
# if / elsif / else
if score >= 90
"A"
elsif score >= 80
"B"
else
"C"
end
# unless (inverse of if)
unless logged_in?
redirect_to login_path
end
# Ternary
status = age >= 18 ? "adult" : "minor"
# Inline / modifier form
puts "hello" if debug
puts "hello" unless silent
# case / when
case command
when "start"
start_engine
when "stop"
stop_engine
when "status"
show_status
else
puts "Unknown command"
end
# case with ranges
case temperature
when 0..15 then "cold"
when 16..25 then "pleasant"
when 26..40 then "hot"
end Loops
Ruby favors iterators over traditional loops, but supports both styles.
# while
i = 0
while i < 5
puts i
i += 1
end
# until (inverse of while)
i = 0
until i >= 5
puts i
i += 1
end
# for..in
for num in [1, 2, 3]
puts num
end
# each (preferred Ruby idiom)
[1, 2, 3].each do |num|
puts num
end
# times
5.times { |i| puts i }
# upto / downto
1.upto(5) { |i| puts i }
5.downto(1) { |i| puts i }
# loop (infinite, use break to exit)
loop do
break if done?
end
# Control flow inside loops
next # skip to next iteration
break # exit the loop
redo # restart current iteration Methods
Methods return the value of their last expression. Parentheses are optional but recommended for clarity.
# Basic method
def greet(name)
"Hello, #{name}!"
end
greet("Alice") #=> "Hello, Alice!"
# Default parameters
def greet(name, greeting = "Hello")
"#{greeting}, #{name}!"
end
# Explicit return
def absolute(n)
return -n if n < 0
n
end
# Variable-length arguments
def log(*messages)
messages.each { |msg| puts msg }
end
# Keyword arguments
def connect(host:, port: 80, ssl: false)
# ...
end
connect(host: "example.com", ssl: true)
# Method with block
def measure
start = Time.now
yield
Time.now - start
end
# Predicate and bang methods (convention)
"".empty? #=> true (returns boolean)
arr.sort #=> new sorted array
arr.sort! #=> sorts array in place Blocks, Procs, and Lambdas
Blocks are anonymous chunks of code. Procs and lambdas store blocks as objects.
# Block (do..end or curly braces)
[1, 2, 3].each { |n| puts n }
[1, 2, 3].each do |n|
puts n
end
# Proc
square = Proc.new { |x| x ** 2 }
square.call(5) #=> 25
# Lambda
double = ->(x) { x * 2 }
double.call(4) #=> 8
# Passing a block to a method
def run_twice(&block)
block.call
block.call
end
# Lambda vs Proc: lambdas check arity and
# return from the lambda, not the enclosing method. Classes and Modules
Classes define objects; modules provide namespacing and mixins.
# Class
class Dog
attr_accessor :name, :breed
def initialize(name, breed)
@name = name
@breed = breed
end
def speak
"Woof! I'm #{@name}."
end
end
rex = Dog.new("Rex", "Labrador")
rex.speak #=> "Woof! I'm Rex."
# Inheritance
class Puppy < Dog
def speak
"Yip! I'm #{@name}."
end
end
# Module as mixin
module Swimmable
def swim
"#{@name} is swimming!"
end
end
class Duck
include Swimmable
def initialize(name)
@name = name
end
end
Duck.new("Daffy").swim #=> "Daffy is swimming!"
# Module as namespace
module Payments
class Invoice
# ...
end
end Comments
Single-line comments use #. Multi-line comments use =begin / =end (rarely used in practice).
# This is a single-line comment
x = 42 # inline comment
=begin
This is a multi-line comment.
It is rarely used; most Rubyists
prefer consecutive # lines instead.
=end Tips for Writing Clean Ruby
Use two-space indentation (not tabs). Prefer each over for. End method names with ? for booleans and ! for destructive operations. Use a good code editor or IDE that understands Ruby syntax -- tools like those compared at whocodesbest.com can help you choose the right AI-powered coding assistant for your workflow.
For deeper coverage of any topic above, explore the full Ruby tutorial on this site.