Sobes.tech
Intern

What is a class in Ruby?

sobes.tech AI

Answer from AI

A class in Ruby is a template or blueprint for creating objects. It defines the structure (attributes) and behavior (methods) that objects created from this class will have.

Main concepts:

  • Object: An instance of a class. Each object has its own attribute values.
  • Attributes (instance variables): Variables that store the state of an object. In Ruby, they start with @.
  • Methods (instance methods): Operations that objects of the class can perform.

Example:

class Dog
  # Instance attribute (state)
  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  # Instance method (behavior)
  def bark
    "#{@name} says Woof!"
  end

  # Getter for attribute access
  def name
    @name
  end
end

# Creating objects (instances of the Dog class)
my_dog = Dog.new("Buddy", "Golden Retriever")
your_dog = Dog.new("Lucy", "Labrador")

# Calling methods on objects
puts my_dog.name # Outputs "Buddy"
puts my_dog.bark # Outputs "Buddy says Woof!"

Classes in Ruby are themselves objects (instances of the Class class) and support inheritance.