Sitemap

Ruby Classes and Objects

2 min readOct 4, 2022

--

Classes and objects are all foundational components within the Ruby language and allows you to understand how your code is working beneath the surface(its internal workings).

Ruby Classes

Ruby is an Object-Orientated language and relies on the concept of classes and objects to structure a program into simple and reusable pieces of code that acts as blueprints to create individual instances of objects. Each time you create a class, you are essentially creating a new data type.

Syntax:

Press enter or click to view image in full size

You need to define what attributes all “Something” has and that information will be provided within the class. This can be anything from (attributes) such as getters and setters (attr_reader, attr_writer, attr_accessor) as well as Associations (has_many and belongs_to).

Ruby Objects

An object is an individual instance of a class (example: a singular “Something”). In Ruby, everything is an object with the exception of conditionals, blocks, and messages so in-turn a class is an object.

Get Leon Wong’s stories in your inbox

Join Medium for free to get updates from this writer.

To create a new Book object you use Ruby’s new method on the class and supply the values for the class’s defined attributes:

We created a new instance of the “Something” class, also known as an object, and assigned it to a variable (first_something) and then used Ruby’s dot notation to assign values to the attributes of the instance.

Recap

So classes define what an instance of that class will look like (somewhat like a blueprint. An instance is an object and methods (defined within the class) that describes what an instance of the class/object will be able to do.

--

--