A Quick Tutorial on using Classes in Ruby

Cedric Patton Jr
3 min readNov 6, 2020
A picture of rubies

Hello my fellow coders! In this article we’ll go over how to set up and use Ruby classes and objects in your text editor. Before we dive into this tutorial I wanted to give a disclaimer and let you guys know that we’ll only be going over how to implement Ruby code. This article doesn’t go in depth on what classes and objects are, only the applications and syntax. If you haven’t learned the about Object Oriented Programming or just need a refresher, then I would recommend learning about that concept first before hopping directly into this code-along. I’ve written an article that covers what OOP is, so feel free to check it out! Okay, let’s go over the steps in creating Ruby classes and objects. We’ll cover these four processes:

  1. Creating and setting up our Class
  2. Creating instances of our class
  3. Calling Methods on our classes

Creating a Class

Define our Class

The first thing we want to do is define a class object. We do this using the class keyword followed by the name of our class, and we close it with the end on the next line. When naming our class, we always make sure to use capitalization, otherwise, our class wouldn’t work. For our example, we will be creating a Sims-esque style program where you can create persons have them do certain actions have certain behaviors.

Defining a class called Person

Create our reader/writer methods

After we define our class, the next step would be to create our reader and writer methods. By creating these methods, we give our class (or our instances of our class rather) various properties and data that we can later access and manipulate.

attr_accessor gives both read and write functionality

Now with our reader/writer methods defined, we’ll be able to check the name, happiness, and hygiene of each character we create. We also be able to check and manipulate their bank account as well.

Create our Initialize Method

This method is invoked automatically whenever a person is created. The created character will have the bank account, happiness level, and hygiene level defined in the initialize upon instantiation.

Create Instance Methods

Now let’s create all the other methods we want to be able to call on an instance of a person.

And that’s it! Now that we have our Person class set up, we can now start creating persons in our terminal!

--

--

Cedric Patton Jr

A coding and motorcycle enthusiast who’s passionate about personal development and learning. Recent Flatiron School of Software Engineering graduate.