Ruby classes & initialize
This course explains how Ruby classes work, using a small BankAccount class and the Article example. It covers class/end as a blueprint, what .new builds, and how .new calls initialize with the arguments it receives. It shows that each object keeps its own instance variables, reachable from outside only through methods. Reader and writer methods are first written by hand, then generated with attr_reader, attr_writer and attr_accessor. The course ends by connecting these pieces to how ActiveRecord generates attribute methods from a table's schema.
What you'll learn
- ✓How class/end defines a blueprint and .new builds separate objects
- ✓How .new calls initialize automatically, with arguments and default values
- ✓Why each object keeps its own copy of its instance variables
- ✓Writing reader methods and writer methods ending in = by hand
- ✓Generating those methods with attr_reader, attr_writer and attr_accessor
- ✓How ActiveRecord generates readers and writers from a table's schema
Classes are blueprints, not objects
The "Ruby variables & assignment" course built a small BankAccount class to explain local versus instance variables, and quietly used it without ever explaining what class and .new do. This course closes that gap.
Read the full lesson free →Curriculum
7 lessonsClasses are blueprints, not objects
A class defines a blueprint, .new builds separate objects from it, and a class is itself an object.
The initialize method
.new calls initialize automatically with its arguments, which work like any method's parameters, including defaults and ArgumentError.
Every object remembers its own state
Each object gets its own copy of its instance variables, and outside code reaches them only through methods.
Reader and writer methods, written by hand
A reader method returns an instance variable, and a writer method whose name ends in = reassigns it.
attr_reader, attr_writer, attr_accessor
attr_reader, attr_writer and attr_accessor generate the same reader and writer methods, each granting only what its name says.
The convenience ActiveRecord was hiding all along
ActiveRecord reads a table's columns, generates a reader and writer for each, and provides an initialize that accepts a hash.
Putting it together: article, written by hand
A PlainArticle class written from scratch combines every lesson, while the < in class Article < ApplicationRecord stays unexplained.