Câu hỏi phỏng vấn Ruby
Câu hỏi

What is a class in ruby?

Câu trả lời

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:

ruby Copy
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:

ruby Copy
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

entry

Gợi ý câu hỏi phỏng vấn

junior

What is the difference between private and protected methods?

junior

Is Ruby a strongly typed or a weakly typed language?

entry

What are rubygems?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào