Ruby Cheatsheet

Pattern Matching and Ruby Idioms

Use this Ruby reference while you build software engineering projects, review code, or refresh the syntax you reach for most.

Safe Navigation and nil Handling

user&.profile&.email      # nil if any receiver is nil
name = input.presence     # Rails only, not core Ruby
name = input unless input.nil? || input.empty?
value ||= fallback        # assigns fallback when value is nil or false

Core Ruby has nil?, safe navigation, and || defaults. Rails adds helpers like present? and presence; do not assume they exist in plain Ruby.

Destructuring Assignment

first, second = [10, 20]
head, *tail = [1, 2, 3, 4]
key, value = [:name, "Ada"]

a, b = b, a              # swap

Extra values are ignored unless captured with *. Missing values become nil.

Keyword Hash Shorthand

name = "Ada"
score = 100
user = { name:, score: }   # Ruby 3.1+

def create_user(name:, score:)
  { name:, score: }
end

Use shorthand when the local variable name and keyword or hash key match.

Pattern Matching case/in

event = { type: "purchase", amount: 20, user: { id: 7 } }

case event
in { type: "purchase", amount:, user: { id: } }
  "user #{id} spent #{amount}"
in { type: "refund", amount: }
  "refund #{amount}"
else
  "ignore"
end

Pattern matching destructures arrays and hashes. It is useful at data boundaries, but ordinary case is often clearer for simple value checks.

Array Patterns

case [200, { ok: true }]
in [200..299, { ok: true }]
  :success
in [400..499, _body]
  :client_error
else
  :other
end

_ names a value you intentionally ignore. Ranges, classes, literals, arrays, and hashes can all participate in patterns.

Method Predicates

user.nil?
items.empty?
text.include?("ruby")
path.end_with?(".rb")
obj.respond_to?(:call)

Predicate methods end with ? by convention and return a truthy or falsey value. Prefer them over manual comparisons when they communicate intent.