Ruby Cheatsheet

Control Flow

Use this Ruby reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

if / elsif / else

if score >= 90
  "A"
elsif score >= 80
  "B"
else
  "keep going"
end

message = if admin
  "allowed"
else
  "blocked"
end

Ruby conditionals are expressions: the whole if returns a value.

Postfix Conditionals

return nil if input.nil?
puts "debug" if ENV["DEBUG"]
next unless item.valid?

Use postfix form for short guard clauses. Avoid it when the condition or body is complex.

unless

unless logged_in?
  redirect_to_login
end

puts "missing" unless value

Prefer if !condition when unless would need an else or a compound condition.

case

case status
when "new"
  "start"
when "paid", "active"
  "ship"
else
  "hold"
end

case value
when Integer then "number"
when String then "text"
when /\A[a-z]+\z/ then "lowercase word"
end

case uses === internally, which is why classes and regexes work in when clauses.

Loops

3.times { |i| puts i }          # 0, 1, 2
1.upto(3) { |n| puts n }        # 1, 2, 3
3.downto(1) { |n| puts n }      # 3, 2, 1
(1..5).each { |n| puts n }

while queue.any?
  process(queue.shift)
end

until done?
  step
end

Prefer Enumerable methods over manual index loops when you are transforming collections.

break, next, redo

items.each do |item|
  next if item.nil?     # skip this item
  break if item == :stop
  puts item
end

tries = 0
begin
  tries += 1
  connect
rescue TimeoutError
  retry if tries < 3
  raise
end

next is Ruby's continue. retry restarts a rescued block; use it carefully.

Boolean Operators

a && b      # and, short-circuit
a || b      # or, short-circuit
!a          # not

user && user.name
user&.name          # safe navigation, nil if user is nil
name || "Guest"     # default when nil or false

Use && and || for normal logic. The words and and or have lower precedence and are mostly useful for control flow like save or raise.