[Ruby] Classes and instances

Introduction In Ruby, you can create new kinds of values yourself, apart from the predefined values.

At that time, you can prepare and create blueprints such as "what kind of characteristics do you have?" And "what kind of operation do you want?"

The concepts needed to create a new kind of value are "classes" </ b> and "instances" </ b>.

What is a class?

The source of the value. You can define common rules for values. The rules defined here are common "attributes" and "processes (methods)" </ b>.

The advantage of using classes is that they are easier to develop, manage, and maintain by grouping common information and separating individual information for each piece of data.

A class is, for example, a blueprint in the manufacture of a car, and the value produced from it is a car. Since the class is just a blueprint, it has no entity and cannot be treated as data by itself. </ b>

The class is defined as follows.

class class name
  #Definition of variables and methods
end

The rule is that the class name starts with a half-width uppercase letter. </ b> (Example) User, Group, etc.

What is an instance? It is the data created based on the class. Instances, unlike classes, have entities and can be used as data. If the class is a blueprint for a car, then the instance is a car generated from it.

Instances are created by executing new methods </ b> that can be used by the class.

What is the new method This is a method that the class has in advance. Creates and returns an instance of the class used.

The usage is as follows.

#Here, an instance is created and assigned to a variable.
Variable name=name of the class.new

Basically, as described above, the created instance is assigned to a variable and reused. This is so that you can add data and execute methods after you instantiate.

Create an instance by actually specifying the class name below

class Car

end

fire_truck = Car.new

You have now created an instance from a class called "Car" and assigned it to a variable called "fire_truck".

Recommended Posts