DEV Community

Cover image for 49 Days of Ruby: Day 20 - Classes
Ben Greenberg
Ben Greenberg

Posted on

49 Days of Ruby: Day 20 - Classes

Welcome to day 20 of the 49 Days of Ruby! 🎉

Today is all about giving Ruby some class, but with a capital "C"!

First, let's define what a class is:

A class is a template for your code.

In the simplest terms, that is precisely what a class is. It gives your code a blueprint that can be used to make something with.

Let's take an example of a blueprint for a dog:

class Dog
end
Enter fullscreen mode Exit fullscreen mode

With the above example, we have created a class, a template for a dog. However, what if we want our future dogs to be part of a certain breed? Right now, our class makes an undefined dog. Let's fix that:

class Dog
  def initialize(breed)
    @breed = breed
  end
end
Enter fullscreen mode Exit fullscreen mode

The #initialize method in Ruby is a special method the language provides that you can use in your class creation to define the elements of your template. You provide #initialize with the items you want every instance of your class to be created with, and when you instantiate those instances, you can define the details for those items then.

Thus, our new Dog class now has a breed attribute. You see that we don't tell the class what kind of breed, just that it should accept a breed during instantiation:

poodle = Dog.new(breed: "poodle")
Enter fullscreen mode Exit fullscreen mode

Now we have a new poodle instance of our Dog class! What if we wanted a bulldog as well? 🐶

bulldog = Dog.new(breed: "bulldog")
Enter fullscreen mode Exit fullscreen mode

Now we also have a bulldog! 🐕‍🦺

What if you want to provide an attribute in your class definition that is true for all future instances? You can do that with a default value. Let's say we wanted all dogs to have a tail:

class Dog
  def initialize(breed, tail = true)
    @breed = breed
    @tail = tail
  end
end
Enter fullscreen mode Exit fullscreen mode

Now, all of our dogs from this class will have a true value for a tail!

That's it for today. Share your learning with the community on classes!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)