Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 134 ยท Object-Oriented Ruby

Classes and Objects

Learn Ruby classes and objects - class, new, initialize, instance variables, attr_reader, attr_writer, attr_accessor, instance methods, to_s and inspect - with runnable examples.

So far you have used objects that Ruby gave you: strings, arrays, hashes, ranges. Each one bundles data (the characters, the elements) with behaviour (the methods you can call on it). A class is the blueprint that lets you create your own kinds of objects with exactly that mix. A Dog knows its name and can bark. A BankAccount knows its balance and can deposit. A Temperature knows its degrees and can convert itself.

Ruby is a purely object-oriented language: every value is an object, and nearly every action is a method call on one. That makes classes the main tool for organising programs larger than a page. This lesson covers defining a class, creating objects with new, setting up state in initialize, instance variables, the attr_* shortcuts, instance methods, and the two methods that control how objects print: to_s and inspect. It builds on Methods and Basic Types.

Your first class

A class is introduced with the keyword class and a name that starts with a capital letter (Ruby makes it a constant). Everything up to the matching end is the body. You create an object with ClassName.new, and each object created this way is called an instance of the class.

Ruby An empty class and its instances

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

rex and fido are two separate objects of the same class, which is why rex == fido is false: by default two objects are equal only if they are the very same object (more in Equality and Identity). Even the class itself is an object: Dog.class is Class.

An empty class is not very useful, so let us give it state and behaviour.

initialize and instance variables

When you call new, Ruby allocates a blank object and then calls its initialize method, passing along whatever arguments you gave to new. That is where you set up the object's starting data. The data lives in instance variables, names that begin with @. Each object has its own set, and they are visible to every method of that object, but not from outside.

Ruby initialize and instance variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each dog keeps its own @age: two birthdays for Rex do not touch Fido. initialize is always private (you cannot call rex.initialize from outside), and its return value is ignored: Dog.new returns the new object, never whatever initialize computes.

Two beginner traps are worth knowing now. First, an instance variable you never assigned is simply nil, with no error, so a typo such as @nmae silently reads as nil. Second, new passes its arguments to initialize unchanged, so a wrong number of them is an ArgumentError:

Ruby Wrong number of arguments (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby reports main.rb:3:in 'Dog#initialize': wrong number of arguments (given 1, expected 2) (ArgumentError). The fix is to pass both arguments, or to give age a default value in the definition (def initialize(name, age = 0)). Everything from Method Arguments, including keyword arguments, works in initialize.

Accessors: attr_reader, attr_writer, attr_accessor

Instance variables are private to the object. To let the outside world look at (or change) them you write methods. Writing them by hand is dull:

Ruby
def name
  @name
end

def name=(value)
  @name = value
end

Ruby generates both with one-line macros:

Macro Creates
attr_reader :name the getter name
attr_writer :name the setter name=
attr_accessor :name both
Ruby Generated readers and writers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

owner and balance can be read but not assigned from outside. nickname has both. A method that ends in = is a setter, and acct.nickname = "x" is just a method call written with nicer syntax. Returning self from deposit lets you chain calls, as in acct.deposit(50).deposit(25).

Trying to assign to a read-only attribute fails, and the message is helpful:

Ruby Assigning to a reader (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby answers main.rb:10:in '<main>': undefined method 'balance=' for an instance of Account (NoMethodError). That is the point of attr_reader: money changes only through methods like deposit that can check the amount.

Inside the class, the rule is: read instance variables directly (@balance) or through the reader, but when you assign through a setter you must write self.nickname = "x". Plain nickname = "x" just creates a local variable and leaves the object unchanged. This is one of the most common beginner bugs.

Methods that use and change state

A class is more than a bag of attributes. Methods let objects protect rules (an invariant) and express intent. Here is a small Temperature class with a validated setter, a computed attribute and a predicate method (ending in ?, by convention returning true or false).

Ruby Validation and computed values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The constructor calls the setter through self.celsius =, so the validation runs from the very first assignment, and no code path can create a colder-than-possible Temperature. fahrenheit has no variable of its own: it is computed on demand, so it can never go out of date. Constants such as ABSOLUTE_ZERO belong to the class and are written in capitals.

to_s and inspect: how objects print

Ruby uses two different methods to turn an object into text.

  • to_s produces the friendly version. puts and string interpolation ("#{obj}") call it.
  • inspect produces the developer version. p and the REPL call it, and so does the default to_s for collections of objects.

By default both print the class name and a memory address, such as #<Dog:0x000...> (with the instance variables too in inspect). That is rarely what you want to show a user. Override whichever you need.

Ruby Custom to_s and inspect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside an array, each element is shown with inspect, even when you call to_s on the array. So a good inspect also makes lists of your objects readable while debugging. The last two lines mask the address (it changes every run) to show the default format: inspect lists the instance variables, to_s does not. More in to_s, inspect and Conversions.

Objects are references

A variable holds a reference to an object, not a copy of it. Assigning one variable to another makes both point at the same object, so a change through one is visible through the other.

Ruby Two names, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

a and b are two names for the same counter. When you need an independent copy, make one explicitly (see Copying Objects). This also explains why passing an object to a method lets that method change it.

Design tips

  • Keep initialize simple. Set instance variables and validate; avoid slow work or side effects like reading files.
  • Prefer small, focused classes. If a class has many unrelated attributes, split it.
  • Expose as little as you need. Start with attr_reader; add a writer only when outside code truly must set the value.
  • Name for meaning. A method called withdraw beats change_balance_by_negative.
  • Make objects valid from the start. If a Temperature cannot exist without a number, require it in initialize.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Dog.new("Rex", 3) do?

    new allocates the object, runs initialize with the arguments, and returns the object itself. The return value of initialize is ignored.
  2. 2. Which line creates both a getter and a setter for @title?

    attr_accessor defines title and title=. The reader and writer macros define only one of the two.
  3. 3. Inside a method of the class, why does balance = 10 not change the object when balance= is a setter?

    A bare name followed by = always creates a local variable. Calling the setter needs an explicit receiver such as self.
  4. 4. Which method does puts obj call to get the text of the object?

    puts and string interpolation call to_s. p calls inspect.
  5. 5. After a = Counter.new; b = a; b.increment, what is true?

    Assignment copies the reference, not the object. Both variables point to the same Counter.

Summary

  • A class is a blueprint; ClassName.new creates an instance and runs initialize with the arguments.
  • Instance variables (@name) belong to each object, are nil until assigned, and are private to it.
  • attr_reader, attr_writer and attr_accessor generate getters and setters; inside the class use self.name = ... to call a setter.
  • A wrong argument count to new raises ArgumentError; assigning to a reader raises NoMethodError.
  • to_s is the friendly text (puts, interpolation) and inspect the developer text (p, lists).
  • Variables hold references, so two names can point at the same object.

Next: Instance and Class Methods