What is a class in ruby?
What is a class in ruby?
In Ruby, a class is a fundamental concept within the realm of object-oriented programming. It acts as a blueprint from which individual objects are created. A class in Ruby defines the properties (attributes) and behaviors (methods) that the objects created from it will possess.
A class encapsulates data for the object and methods to manipulate that data, effectively organizing and structuring code to model real-world entities or concepts programmatically. For instance, you might have a Book
class in a library management system, where each instance of the Book
class represents a specific book with properties like title, author, and ISBN, and methods to perform actions like checking out the book or updating its location.
Here’s a simple example of a class in Ruby:
class Car
attr_accessor :make, :model, :year
def initialize(make, model, year)
@make = make
@model = model
@year = year
end
def start
puts "The car is starting."
end
end
In this example:
Car
is the class.@make
, @model
, and @year
are instance variables.attr_accessor
provides getter and setter methods for the instance variables.initialize
is a special method that gets called when a new object is instantiated. It sets the initial state of the object.start
is a method that all instances of the class can perform.When you create a new instance of a class, you are creating an object that includes all the methods and properties defined in the class. For example, creating an instance of the Car
class might look like this:
my_car = Car.new("Toyota", "Corolla", 2021)
my_car.start # Outputs: The car is starting.
In Ruby, classes themselves are objects—they are instances of the clas...
entry
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào