Ruby Basics : Class

Class

In this article, you will the learn the basics of a class and how to define them in a program. We will look at the concept of car and how to represent a car in a program.

Concept of Car

A car has attributes such as color, price, model and so on. You can exercise certain behavior such as drive, stop, turn, etc on a car.

Car Concept

Representing a Car

We can represent the concept of a car using a class.

Car Class

A class has a class name. In this example, the class name is Car.

Defining a Class

Let's define a Car class.

class Car
end

Car

We use the class keyword followed by the class name to define a class. In this case, Car is the class name.

Representing the Behavior

We can represent the drive behavior of a car by defining a drive() method for the Car class.

class Car
  def drive()
    return 'driving'
  end
end

Defining a Method

The methods provide the behavior for the objects. We use the def keyword followed by the method name to define a method. The body of the method becomes the implementation.

Car Class Analogy

A Car class is like a car blueprint.

Car Blueprint

A car blueprint is used to manufacture many cars.

Key Takeaways

  • A car class acts as a template used to create cars.
  • A car class describes the behavior and attributes of a car.

Exercise

Define a method in the Car class to stop a car.

Summary

In this article, you learned the concept of class. A class describes the behavior and attributes of a certain concept.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.