Thuta Learning
Ruby
AdvancedProgrammingBeginner

OOP Intro

RubyLesson 1630 min

What you'll walk away with

  • Describe an object as state (instance variables) plus behaviour (methods)
  • Read obj.method(args) as sending a message, and use .class and respond_to?
  • Tell a class from an instance and understand the error from Car.drive versus car.drive
  • Explain encapsulation, abstraction, inheritance, polymorphism and duck typing
  • Know that nil is an object and interpret NoMethodError: undefined method ... for nil

Explain it simply

Explain it simply

An object is a thing that carries both its own facts and the things it can do. Think of a car: it has facts it remembers, such as its brand and how much fuel it has (its state), and it can do things such as drive and refuel (its behaviour). A program can model it the same way, and writing car.drive(20) means sending the message drive to the car object.

What makes Ruby special is that everything is an object: numbers, strings, arrays, true and even nil. So learning to write your own classes is not learning a new system; you are building more of the same kind of thing you have been using all along.

Problem → Why → Solution

The problem: data and the code that uses it live apart

You have probably modelled a car with a hash and written a function that changes it. That feels easy at first, but a hash is just a bag that accepts anything. In the code below the key name is mistyped as :fule instead of :fuel, and Ruby does not complain, because reading a missing key from a hash quietly returns nil. Nothing fails until the program tries to compute nil - 10.

car_hash.rb
car = { brand: "Toyota", fuel: 10 }

def drive(car, km)
  car[:fule] -= km / 2    # typo: the key is :fuel
end

drive(car, 20)
# NoMethodError: undefined method '-' for nil

What an object changes

When the hash and the function live apart, the knowledge that a car has fuel and can drive is smeared across the whole program, and any function can touch any key. An object gathers the data and the only code allowed to touch it in one place. A bug then lives inside one small class, and the rules can be checked in one spot.

Core concept: objects, messages and classes

Object-oriented programming is organising a program as objects that talk to each other by sending messages. An object bundles state (the data it remembers, kept in instance variables) with behaviour (the methods that read or change that state). When you write car.drive(20) you send the message drive, with the argument 20, to the object car, and the object decides how to respond.

In Ruby everything is an object: numbers, strings, symbols, ranges, true, false and even nil. 5 + 3 is really the message + sent to the object 5 with the argument 3, which you can also write as 5.+(3). Every object belongs to a class, which you can ask for with .class, and the class decides which messages the object understands. respond_to? asks whether an object understands a message without sending it.

A class is the blueprint, and an object (also called an instance) is one thing built from it. Car is the class; the red Toyota in front of you and the blue Honda next door are two instances. They share the class's methods (behaviour) but each keeps its own instance variables (state), so driving one car does not move the other.

Four ideas keep coming up. Encapsulation means an object guards its own state and exposes a small set of methods. Abstraction means callers use drive without knowing how the engine works. Inheritance lets one class build on another, which a later lesson covers. Polymorphism means different objects answer the same message in their own way; Ruby needs no shared parent for this, only that the objects answer the same method name, which is called duck typing: if it quacks like a duck, treat it as a duck.

Even nil is an object, the only instance of NilClass. That is why calling a method nil does not have produces NoMethodError: undefined method 'upcase' for nil. When you see that message, the real question is not why upcase is missing but why this value is nil.

Mental model: objects receive messages
  1. Sender writes object.message(args)
  2. Ruby finds the method in the class
  3. Method uses the object's own state
  4. Result goes back to the sender

When an object receives a message it does not understand, Ruby raises NoMethodError, which is how misspelled method names and calls on nil show up.

General pattern

ruby
receiver.message                # no arguments
receiver.message(arg1, arg2)    # with arguments
receiver.message { |x| ... }    # with a block
receiver.respond_to?(:message)  # can it handle this message?
receiver.class                  # which class is it an instance of?

The left side of the dot is the receiver, the object that gets the message, and the right side is the message, the method name. Arguments go in parentheses and a block can follow. respond_to? and class are two ways of questioning an object before you send it anything.

Example: asking everything what it is

This example puts eight different values in one array and asks each of them for its .class. The result shows that numbers, strings, symbols, nil, true, arrays and ranges are all objects, each with a class of its own.

In the lower half, see that 5 + 3 is the same as 5.+(3), and watch respond_to? answer without sending the message.

everything_is_an_object.rb
values = [42, 3.5, "ruby", :sym, nil, true, [1, 2], 1..3]

values.each do |value|
  puts "#{value.inspect.ljust(8)} -> #{value.class}"
end

puts 5 + 3
puts 5.+(3)
puts 5.respond_to?(:+)
puts "ruby".respond_to?(:upcase)
puts nil.respond_to?(:upcase)

Code breakdown

  1. classvalue.class

    Every object can be asked for its .class. 42 is an Integer, 3.5 a Float, nil a NilClass and true a TrueClass, all ordinary classes.

  2. inspectvalue.inspect.ljust(8)

    inspect shows a value the way you would write it in code ("ruby" keeps its quotes and :sym its colon). ljust(8) pads to eight characters so the arrows line up. Notice that these are method calls chained one after another.

  3. messageputs 5.+(3)

    5 + 3 looks like an operator but is really the message + sent to the object 5 with the argument 3, so 5.+(3) also gives 8. Ruby just lets you write the friendlier 5 + 3.

  4. respond_to?puts nil.respond_to?(:upcase)

    respond_to? asks whether the object understands that message. nil does not understand upcase, so the answer is false; actually calling upcase would raise NoMethodError, but here we only ask, so nothing breaks.

You should see
42       -> Integer
3.5      -> Float
"ruby"   -> String
:sym     -> Symbol
nil      -> NilClass
true     -> TrueClass
[1, 2]   -> Array
1..3     -> Range
8
8
true
true
false

Two objects, two separate states

Here is the car from the problem section rewritten as a class. initialize stores the brand and fuel when the object is built, and the Initialize lesson explains it in full. Toyota and Honda use the same drive method but each keeps its own @fuel, so they burn fuel independently. One honest caveat: a mistyped instance variable name also reads as nil in Ruby, so the main gain is that every place such a bug can live is confined to one small class.

two_cars.rb
class Car
  def initialize(brand, fuel)
    @brand = brand
    @fuel = fuel
  end

  def drive(km)
    @fuel -= km / 2
    "#{@brand} drove #{km} km, fuel left: #{@fuel}"
  end
end

toyota = Car.new("Toyota", 10)
honda = Car.new("Honda", 8)
puts toyota.drive(10)    # Toyota drove 10 km, fuel left: 5
puts honda.drive(4)      # Honda drove 4 km, fuel left: 6
puts toyota.drive(10)    # Toyota drove 10 km, fuel left: 0

The four ideas and duck typing

IdeaWhat it meansIn Ruby
EncapsulationAn object guards its state and offers a few methodsInstance variables are reached only through methods
AbstractionCallers use what an object does, not howcar.drive(10) hides the fuel arithmetic
InheritanceOne class builds on anotherclass Truck < Car (a later lesson)
PolymorphismDifferent objects answer one message in their own wayspeak on a Dog and on a Robot

In the code below Dog, Cat and Robot share no parent class; they only happen to have a method called speak. Still, the loop that sends speak to each of them works for all three, and that is duck typing. Ruby does not check the class name; if an object understands the message, it is good enough. For an object that might lack speak you can ask first with respond_to?.

duck_typing.rb
class Dog
  def speak
    "Woof"
  end
end

class Cat
  def speak
    "Meow"
  end
end

class Robot
  def speak
    "Beep"
  end
end

[Dog.new, Cat.new, Robot.new].each { |thing| puts thing.speak }   # Woof, Meow, Beep
puts 42.respond_to?(:speak)                                       # false

nil is an object too

nil belongs to the class NilClass and understands a handful of methods itself (nil.to_s is "" and nil.to_a is []). It does not understand string methods such as upcase. In Ruby 4.0.9 the error message is undefined method 'upcase' for nil; the wording was a little different in older versions. When you know a result may be nil, the safe navigation operator &. skips the call and returns nil if the receiver is nil. Sprinkling &. everywhere without asking why nil arrived is not a good habit, though.

nil_object.rb
name = nil
p name.class          # NilClass
p name.nil?           # true
p name.to_s           # ""
p name.to_a           # []

begin
  name.upcase
rescue NoMethodError => e
  puts e.message      # undefined method 'upcase' for nil
end

p name&.upcase        # nil  (&. skips the call when the receiver is nil)

In real projects

Where this shows up in real projects

Almost every Ruby program is built from objects. In a Rails app each row of the database becomes a model object such as User or Order, with its own data (email, total) and behaviour (activate!, paid?). Controllers send messages to those objects, and service objects package one big task as a named class. In gems like Sidekiq you write a worker class with a perform method and it becomes a background job.

Duck typing makes testing easier: to test a payment service you can hand it a fake object that answers charge instead of a real payment gateway, with no shared parent needed. The price is that the call site must make clear which method it relies on, so give each class one clear responsibility. When you read unfamiliar code, asking what objects exist, what each one knows and what each one can do is a very useful way to start.

Common mistakes

Common mistakes

1. Using bare hashes where an object belongs

If a hash models a car and ten functions change its keys directly, nobody catches a misspelled name, because a hash returns nil for a missing key. Collect the scattered rules into one class so that validation and defaults live in a single place.

2. Calling a method on nil

NoMethodError: undefined method 'upcase' for nil is one of the most common errors in Ruby. The fix is not to rescue it on the failing line but to trace where the nil came from: a method that forgot to return, a wrong hash key, or missing input. Use &. only when nil is a genuinely expected value.

3. Mixing up the class and an instance

If class Car defines def drive, drive is an instance method, and calling it on the class itself with Car.drive(3) raises undefined method 'drive' for class Car. Build an object first: Car.new.drive(3). The reverse also happens; a missing method on an instance reads undefined method 'fly' for an instance of Car, so the wording of the message tells you whether Ruby saw a class or an instance.

4. Putting everything in one giant class

Object-oriented design does not mean writing as much code as possible in classes; it means small objects with one clear job each. If a single User class logs in, sends email, bills customers and builds reports, you can no longer tell what any change will break. If you cannot say what a class is for in one sentence, it is time to split it.

Best practices

Best practices

  • Name classes with nouns (Car, Invoice) and methods with verbs (drive, total) so that calls read like sentences.
  • Change an object's state only through its methods and do not reach into its data from outside.
  • Give each class one responsibility; if describing it needs an 'and', split it.
  • When NoMethodError appears, ask what the receiver is and whether it is nil before blaming the method name.

Mini challenge

Mini challenge: duck-typed notifiers

Write three notifiers that send a message when a build finishes. The classes share no parent but all answer the deliver message. Also handle one object (42) that cannot deliver.

  • Write EmailNotifier, SmsNotifier and ConsoleNotifier, each with deliver(text) returning a String (Sms keeps only the first 10 characters, Console upper-cases)
  • Write notify_all(targets, text), which sends the deliver message to each target and prints the result
  • Check with respond_to?(:deliver) and print "skipped: <class>" for an object that cannot deliver
  • Call it with the three notifiers plus 42 and the text "Build finished successfully"
notifiers.rb
class EmailNotifier
  # TODO: deliver(text) returns a String that starts with "email   -> "
end

class SmsNotifier
  # TODO: deliver(text) keeps only the first 10 characters of text
end

class ConsoleNotifier
  # TODO: deliver(text) upper-cases the text
end

def notify_all(targets, text)
  # TODO: for each target, deliver if it can, otherwise print "skipped: <class>"
end

# TODO: call notify_all with the three notifiers and 42

Expected: email -> Build finished successfully sms -> Build fini console -> BUILD FINISHED SUCCESSFULLY skipped: Integer

Show hint

text[0, 10] takes up to ten characters. Test target.respond_to?(:deliver) in an if, and print target.class in the else branch; 42.class is Integer.

Show solution
notifiers.rb
class EmailNotifier
  def deliver(text)
    "email   -> #{text}"
  end
end

class SmsNotifier
  def deliver(text)
    "sms     -> #{text[0, 10]}"
  end
end

class ConsoleNotifier
  def deliver(text)
    "console -> #{text.upcase}"
  end
end

def notify_all(targets, text)
  targets.each do |target|
    if target.respond_to?(:deliver)
      puts target.deliver(text)
    else
      puts "skipped: #{target.class}"
    end
  end
end

notify_all([EmailNotifier.new, SmsNotifier.new, ConsoleNotifier.new, 42],
           "Build finished successfully")

Quick quiz 1 / 3

Which expression is exactly equivalent to 8 - 3?

Quick quiz 2 / 3

class Car has just one instance method, drive. Which of these raises NoMethodError?

Quick quiz 3 / 3

Which statement about duck typing is true?

What to remember

  • An object bundles state (instance variables) and behaviour (methods), and obj.method(args) sends a message; even 5 + 3 is 5.+(3).
  • Everything in Ruby is an object, including nil, true, numbers and strings, and you can question objects with .class and respond_to?.
  • A class is the blueprint and an instance is one thing with its own state; Car.drive and car.drive are not the same call.
  • Polymorphism and duck typing mean anything that understands the message will do, and calling upcase on nil raises NoMethodError, so trace why the value is nil.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

OOP Intro | Thuta Learning