Ruby Programming and Penguins

Amy Mangor
2 min readJun 4, 2021

A class in Ruby contains all the specifications needed to create objects. It is like a blueprint for creating objects with each object as its own individual item, with its own data and id. A blueprint for a house contains the information on how to build a house, but a blueprint is not the actual house.

Let’s pretend our class is a colony of African penguins, like the one in the photo below.

Photo by Chance Brown on Unsplash

A penguin colony has lots of penguins, but the colony itself is not a penguin. The class provides what attributes ALL penguins have in common, for example ‘species’ and ‘gender’.

In this way we could write class methods to access information on the class as a whole. For example, if we wanted to know the number of penguins in the entire colony, we would write a class method in order to accomplish this.

class Penguinattr_accessor :species, :gender#attr_accssor is both a getter and setterdef initialize(species, gender)@species = species@gender = gender@@all = []@@all << selfend#self in the following is the class itself. self. indicates a class method.def self.all@@all #this method reads the data that is stored in the classenddef self.countself.all.count #this method will return the number of penguin instances in the classendend

We don’t always want information on the class as a whole. There are times when we want to access information on a single penguin, or an instance of a penguin. A zookeeper might use this to find the largest penguin in the colony, or the name of a specific penguin. In this case we need to use an instance method that will only return the information for a particular instance of a penguin, not the whole colony.

Photo by Sarah Kilian on Unsplash

If we wanted to find out the species of a specific penguin we would write an instance method:

def say_species"Hello friends! I'm a #{species} penguin!"end

And that in a nutshell is how to think about class methods vs instance methods in Ruby using penguins as an example.