Menu
Coddy logo textTech

Defining Classes

Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 2 of 57.

A class describes a kind of object: what it knows and what it can do. class Dog ... end declares the class, and Dog.new creates an object of that class, an instance. A method defined with def inside the class can be called on every instance:

class Dog
  def speak
    "Woof"
  end
end

rex = Dog.new
puts rex.speak
puts rex.class

Output:

Woof
Dog

new creates the object and then calls its initialize method with the arguments you gave to new. initialize sets the object up, usually by storing the arguments in instance variables, whose names start with @:

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

  def speak
    "#{@name} says Woof"
  end
end

puts Dog.new("Rex").speak
puts Dog.new("Bella").speak

Output:

Rex says Woof
Bella says Woof

Methods take arguments like any Ruby method and return the value of their last expression. Every call to new builds a separate object:

class Calculator
  def add(a, b)
    a + b
  end

  def average(numbers)
    numbers.sum.to_f / numbers.size
  end
end

calc = Calculator.new
puts calc.add(2, 3)
puts calc.average([1, 2, 3, 6])

Output:

5
3.0

Class names are constants written in CamelCase (BankAccount); method and variable names use snake_case (deposit_money). new checks its arguments against initialize, so a missing argument raises ArgumentError:

class Point
  def initialize(x, y)
    @x = x
    @y = y
  end
end

begin
  Point.new(1)
rescue ArgumentError => e
  puts e.message
end

Output:

wrong number of arguments (given 1, expected 2)
challenge icon

Challenge

Easy

Complete the class Formatter. Its method title(text) returns the text with every word capitalized (the hobbit gives The Hobbit), slug(text) returns the words in lower case joined by - (the-hobbit), and initials(text) returns the first letter of each word in upper case (TH).

The supplied code creates one Formatter and, for every input line, prints the three results on separate lines.

Your code goes in formatter.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'formatter'

# Supplied input/output code: keep it as it is
input = []
while (line = gets)
  input << line.chomp
end
formatter = Formatter.new
input.each do |line|
  puts formatter.title(line)
  puts formatter.slug(line)
  puts formatter.initials(line)
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Ruby compiler