Intern
What is a class in Ruby language?
sobes.tech AI
Answer from AI
A class in Ruby is a template or blueprint for creating objects. It defines the structure (data/attributes) and behavior (methods) that instances of this class will have.
Key features:
- Encapsulation: Combines data and methods that operate on this data into a single entity.
- Inheritance: Allows creating new classes (subclasses) based on existing ones (superclasses), inheriting their characteristics and behavior.
- Polymorphism: Enables objects of different classes to respond to the same method call in a way specific to their type.
Example of a simple class:
class Dog
# Class constructor
def initialize(name, breed)
@name = name # Instance attribute
@breed = breed # Instance attribute
end
# Instance method
def bark
"#{@name} says Woof!"
end
# Getter for attribute
def name
@name
end
end
# Creating an instance of the class (object)
my_dog = Dog.new("Bobby", "Mixed")
# Calling an instance method
puts my_dog.bark # Output: Bobby says Woof!
puts my_dog.name # Output: Bobby
Classes in Ruby are first-class objects, and they can also be modified dynamically.