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.classOutput:
Woof
Dognew 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").speakOutput:
Rex says Woof
Bella says WoofMethods 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.0Class 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
endOutput:
wrong number of arguments (given 1, expected 2)Challenge
EasyComplete 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler