Ruby Programming and Penguins

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 Penguin

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

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

--

--

Software Engineering Student at Flatiron School

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store