Labs ICT
โญ Pro Login

Classes and Instances

Creating your own types.

Classes and Instances

Use the class keyword to define a class. The initialize method is your constructor โ€” it runs when you call .new.

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

my_dog = Dog.new("Rex", "Labrador")

Use attr_reader, attr_writer, or attr_accessor to generate getter and setter methods so you don't have to write them by hand:

class Dog
  attr_reader :name
  attr_accessor :mood

  def initialize(name)
    @name = name
    @mood = "happy"
  end
end

dog = Dog.new("Rex")
dog.name    # => "Rex"
dog.mood    # => "happy"
dog.mood = "sleepy"

Define methods with def. Use self to refer to the current instance. For class methods, prefix the method name with self.:

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

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

  def self.species
    "Canis familiaris"
  end
end

Dog.species  # => "Canis familiaris"

Inheritance is done with <. Use super to call the parent's version of a method:

class Puppy < Dog
  def initialize(name)
    super(name)
    @mood = "hyper"
  end
end

Override to_s to control how your object looks when printed or interpolated into a string:

class Dog
  def to_s
    "Dog: #{@name}"
  end
end

puts Dog.new("Rex")  # => Dog: Rex
Try it Yourself ->

๐Ÿงช Quick Quiz

What keyword defines a class?