Defining Classes
Everything in Ruby is an object, and every object is an instance of a Class. You define a class using the
class keyword.ruby
Wait! The
initialize method is the constructor. It runs automatically when you call User.new.Attribute Accessors (attr_...)
In Ruby, instance variables are private by default. To make them readable or writable from outside, you use Attribute Accessors.
ruby
Inheritance (<)
Ruby supports Single Inheritance. Use the
< symbol to inherit from a base class.ruby
Modules and Mixins
A Module is a collection of methods and constants, but it cannot be instantiated. Modules have two primary uses:
- Namespacing: Keeping your code organized and avoiding name collisions.
- Mixins: Using the
includekeyword to "mix in" the module's methods into a class. This is Ruby's answer to multiple inheritance!
ruby
Summary
| Term | Description |
|---|---|
| initialize | The constructor method |
| @var | Instance variable (Object state) |
| attr_acc. | Automatic getters and setters |
| include | Adding module methods as instance methods |
| extend | Adding module methods as class methods |
| Best For | Organizing complex logic and data modeling |
| Logic | "Encapsulate state, expose behavior" |
| Safety | Access control with private and protected keywords |
| Modern | Ruby 3.x introduced "RBS" for optional static typing |
| Standard | Use PascalCase for Classes and Modules |
| Identity | A class is also an object (instance of Class) |
| Mixins | Favor small, focused modules over deep inheritance |