Skip to content
Classes and Objects
step 1/7

Reading — step 1 of 7

Learn

~3 min readClasses, Inheritance, Modules

Ruby is fully object-oriented — everything is an object, even integers and nil. Defining classes is essential. The Pickaxe treats this chapter as foundational; you'll use these patterns from the second day of writing Ruby.

Defining a class

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
  
  def greet
    "Hi, I'm #{@name} and I'm #{@age}"
  end
end

ada = Person.new("Ada", 36)
puts ada.greet           # Hi, I'm Ada and I'm 36
  • class Person opens the class (or creates if new)
  • initialize is the constructor — called by Person.new(...)
  • @name is an INSTANCE VARIABLE — visible to all methods on this instance
  • end closes blocks — not braces, indentation, or anything fancier

Reopening classes (a Ruby specialty)

class String
  def shout
    upcase + "!"
  end
end

puts "hello".shout       # HELLO!

You can reopen ANY class, even built-in ones. Add methods, override behavior. Powerful but dangerous — avoid for built-ins in production code (called "monkey-patching").

attr_accessor — the boilerplate-killer

Without it:

class Person
  def initialize(name)
    @name = name
  end
  def name; @name; end           # getter
  def name=(value); @name = value; end    # setter
end

With attr_accessor:

class Person
  attr_accessor :name
  def initialize(name)
    @name = name
  end
end

p = Person.new("Ada")
puts p.name             # Ada
p.name = "Linus"
puts p.name             # Linus
  • attr_accessor :name — both reader and writer
  • attr_reader :name — reader only (read-only attribute)
  • attr_writer :name — writer only (rare)

Multiple at once: attr_accessor :name, :age, :email.

self — the current object

Inside an instance method, self is the instance:

class Person
  def grow_up
    self.age = self.age + 1     # works, but Ruby usually doesn't need self
    @age += 1                    # idiomatic — direct ivar access
  end
end

Use self when the method conflicts with a local variable, or when you need the writer (self.x = ... for assignments).

Class methods (callable on the class itself)

class MathHelper
  def self.double(n)        # def self.X — class method
    n * 2
  end
end

puts MathHelper.double(5)     # 10 — no instance needed

Like Java's static methods. Useful for factory methods, utility functions tied to a type.

to_s — string representation

class Money
  def initialize(cents)
    @cents = cents
  end
  def to_s
    sprintf("$%.2f", @cents / 100.0)
  end
end

puts Money.new(12345)         # $123.45 — to_s called automatically

Override to_s for clean string output. inspect is similar — used by p (debug print) and the REPL.

Common mistakes

  • Forgetting @ on instance varsname without @ is a local variable or method call.
  • Defining methods called to_s that don't return strings — Ruby crashes when something tries to print.
  • Reopening core classes in production code — pollution affects all callers.
  • def name= without self. to call — assigning to an attribute requires self.name = x. Without self, Ruby creates a local var.
  • Using attr_accessor for derived data — those need explicit methods, not auto-generated.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…