When studying programming, you need to learn the basic concepts. In Ruby, many terms such as "object" and "variable" come out and it is difficult, so I would like to output it in my own way to speed up understanding even little by little. I would be grateful if you could point out if there is something like "This is different!"
In order to understand classes and instances in the first place, we need to understand the terms "object" and "method". A rough explanation is from the following.
It means "all data in Ruby". For example, characters such as "good morning" are called "character string objects", and numbers such as "139" are called "numeric objects".
The ** "processing" ** of an object is called a method. Every Ruby object has a "method". For example, like this -Character string object-> length method-> count the number of characters ・ Numerical object → to_s method → Convert to character string And so on, ** the methods that each object type has are different **. For example, ** the techniques that each monster can use are different depending on the monster **.
The introduction has become long, but the main subject is from here. A class is a "** collection of common properties and methods " and is often compared to a " car blueprint ". When you make a car, you need a blueprint, but there is something in common with all cars (such as "accelerating" with the steering wheel and brakes). That is " Let's put together the common parts in a blueprint **". In other words, it is a mechanism that allows you to create a class (blueprint) so that you can use it when making other cars. This is convenient.
An instance is an "object ** created by inheriting attributes and processing from a class **". Is it easy to understand an object (car) created based on a class (blueprint)? Since we have inherited the minimum necessary parts, we interpret that it is an advantage that "there is a handle" ** you do not have to make a blueprint from scratch **.
When I actually write the code, it looks like this.
ruby.rb
class Apple(name of the class)
#Method definition
end
Enclose it in class and end and you're done.
You can create an instance like this.
#Specify the class name with the new method and define it in the variable
orange(Variable name) = apple(name of the class).new
Furthermore, the defined instance is output like this.
puts orange
And if you type ruby filename.rb
in the terminal, it will be executed.
By writing an article like this, I thought it was very good to be able to sort out things that I didn't understand. I plan to write it on a regular basis, so it will be encouraging for me to see it if you like. Thank you for visiting!
Recommended Posts