Ruby Cheatsheet

Methods and OOP

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

Method Definitions

def add(a, b)
  a + b
end

def greet(name = "friend")
  "Hello, #{name}!"
end

def tag(name:, active: true)
  active ? "#{name}:active" : "#{name}:inactive"
end

def sum(*nums)
  nums.sum
end

def build(**options)
  options
end

Ruby returns the last expression automatically. Use explicit return mostly for guard clauses.

Argument Types

SyntaxMeaning
a, brequired positional arguments
name = "friend"default positional argument
*numsgather extra positional args into an array
name:required keyword argument
active: truekeyword arg with default
**optionsgather extra keyword args into a hash
&blockcapture caller's block as a Proc

Classes

class User
  attr_reader :name
  attr_accessor :email

  def initialize(name, email: nil)
    @name = name
    @email = email
  end

  def greeting
    "Hello, #{@name}!"
  end
end

user = User.new("Ada", email: "ada@example.com")
user.name
user.email = "ada@lovelace.test"

Instance, Class, and Module Methods

class Counter
  def initialize
    @count = 0
  end

  def increment
    @count += 1
  end

  def self.zero
    new
  end
end

Counter.zero       # class method
Counter.new.increment # instance method

Visibility

class Report
  def render
    header + body
  end

  private

  def header
    "Title\n"
  end

  def body
    "Content\n"
  end
end

private methods are implementation details. Keep public APIs small.

Inheritance and super

class Animal
  def initialize(name)
    @name = name
  end

  def speak
    "..."
  end
end

class Dog < Animal
  def speak
    "#{@name} says woof"
  end
end

Ruby supports single inheritance. Prefer composition and modules when inheritance would create a fragile hierarchy.

Modules and Mixins

module Sluggable
  def slug
    name.downcase.gsub(/[^a-z0-9]+/, "-").gsub(/^-|-$/, "")
  end
end

class Course
  include Sluggable
  attr_reader :name
end

include adds instance methods. extend adds methods to one object or class object.

Duck Typing

Ruby cares what an object can do, not what class it is.

def print_name(obj)
  puts obj.name
end

If obj responds to name, the method works. Use respond_to? at boundaries when you need a clear error or fallback.