Reading — step 1 of 7
Learn
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 Personopens the class (or creates if new)initializeis the constructor — called byPerson.new(...)@nameis an INSTANCE VARIABLE — visible to all methods on this instanceendcloses 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 writerattr_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 vars —namewithout@is a local variable or method call. - Defining methods called
to_sthat don't return strings — Ruby crashes when something tries to print. - Reopening core classes in production code — pollution affects all callers.
def name=withoutself.to call — assigning to an attribute requiresself.name = x. Withoutself, Ruby creates a local var.- Using
attr_accessorfor 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…