DEV Community

Dylan Rhinehart
Dylan Rhinehart

Posted on

An Introduction to Classes in Ruby: A Guide to Object-Oriented Programming

Ruby is an object-oriented programming language, and classes play a crucial role in this paradigm. A class is a blueprint that defines objects and their behavior. In this article, we'll dive into the basics of classes in Ruby and how they can help you organize and manage your code.

To start, let's take a look at a simple class in Ruby:

class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  def bark
    puts "Woof!"
  end
end
Enter fullscreen mode Exit fullscreen mode

Here, we've created a class called Dog with two attributes: name and breed. The initialize method is a special method that is called when a new instance of the class is created. This is where you can set the initial state for the object. In our example, we are setting the name and breed attributes when a new Dog instance is created.

Creating an instance of the class is simple. Just use the following code:

dog = Dog.new("Fido", "Labrador")
Enter fullscreen mode Exit fullscreen mode

And to call the bark method on the dog object, use the following code:

dog.bark
# Output: Woof!
Enter fullscreen mode Exit fullscreen mode

In addition to the initialize method, Ruby has other special methods that make it easy to define getters and setters for class attributes. For example, you can use attr_reader, attr_writer, and attr_accessor to access and modify the state of an object.

Here's an example of using attr_reader and attr_writer:

class Dog
  attr_reader :name
  attr_writer :breed

  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  def bark
    puts "Woof!"
  end
end
Enter fullscreen mode Exit fullscreen mode

With attr_reader and attr_writer, you can access the name and breed attributes directly:

dog = Dog.new("Fido", "Labrador")
puts dog.name
# Output: Fido

puts dog.breed
# Output: Labrador

dog.breed = "Golden Retriever"
puts dog.breed
# Output: Golden Retriever
Enter fullscreen mode Exit fullscreen mode

And if you want both getter and setter methods, you can use attr_accessor:

class Dog
  attr_accessor :name, :breed

  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  def bark
    puts "Woof!"
  end
end
Enter fullscreen mode Exit fullscreen mode

These are the basics of classes in Ruby, but they will give you a solid foundation to build upon. By using classes in your Ruby programs, you'll be able to create objects, manage their state, and define their behavior, making your code easier to organize and maintain.

Top comments (0)