AnyCompiler

Classes and Objects

A Ruby class is defined with class ... end. initialize is the constructor — it runs automatically when you call ClassName.new(...). Instance variables are written with an @ prefix (@name) and are automatically private to the object; nothing outside the class can read @name directly without a method that exposes it (the next lesson covers the idiomatic way to do that).

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

  def bark
    "#{@name} says Woof!"
  end
end

rex = Dog.new("Rex")
puts rex.bark
puts rex.class
Output
Rex says Woof!
Dog

rex.class confirms rex really is an instance of Dog, a class you just defined — and because of lesson 5, that's not a special case; your own classes sit in exactly the same object system as Integer, String, and nil. Next: attr_accessor and encapsulation — Ruby's idiomatic getter/setter generator.

Practice exercise

Define class Dog with initialize(name) storing @name, and a bark method returning "#{@name} says Woof!". Create Dog.new("Rex") and print its bark.