Classes and objects
Ruby is object-oriented through and through: every value is an object, and every object belongs to a class. Defining your own classes lets you group data with the methods that work on it, like a BankAccount that knows how to deposit and withdraw.
Defining a class
Dog.new(…)creates an object and callsinitializewith the arguments.- Instance variables (
@name) belong to each object and are private to it. - Class names are
CamelCaseand are constants.
Attributes: getters and setters
Instance variables can't be read from outside. Expose them with accessor methods, and Ruby generates them for you:
| Macro | Generates |
|---|---|
attr_reader :x |
def x = @x |
attr_writer :x |
def x=(v) = @x = v |
attr_accessor :x |
Both |
kb.stock -= 3 calls the stock getter and then the stock= setter: in Ruby, even assignment to an attribute is a method call.
to_s, inspect and comparing objects
to_sis used byputsand interpolation;inspectbyp.- Operators are just methods: define
+,==or<=>and they work. - Define
<=>and includeComparableto get<,>,between?,clamp, sorting andmaxfor free.
Class methods and class-level data
Methods defined with self. belong to the class itself, not to each object. They're used for constructors and helpers:
Inheritance
A class can inherit from another and add or change behaviour:
super calls the same method in the parent class. Ruby has single inheritance (one parent). Sharing behaviour between unrelated classes is done with modules, in the next lesson.
Public, private and protected
- public (the default): callable by anyone.
- private: only callable from inside the object, without an explicit receiver.
- protected: callable by other objects of the same class, which is useful for comparisons.
Data classes: Struct and Data
For simple value objects, skip the boilerplate:
Data (Ruby 3.2+) is ideal for small immutable values like coordinates, money or API results.
Practice
- Write a
BankAccountclass withdeposit,withdraw(refusing overdrafts) and abalancereader. - Give it a
to_sthat prints likeAsha: ₹1,250.00. - Create
SavingsAccount < BankAccountthat adds interest withadd_interest(rate). - Define a
Temperatureclass with<=>andComparable, and sort an array of them.
1.What does initialize do?
2.What does attr_accessor :age generate?
3.What does super do inside a method?
4.How do you make a method callable only from inside the object?