variable

Use the same value over and over

Until now, every time I used a value, I think I wrote it every time, even if it was the same value.

However, it is troublesome to write the same value every time. For example, when creating a program that calculates the area of a circle, writing the value of pi each time is a very difficult task.

[Example] Write the same value every time


#Area of a circle with radius 3
3 * 3 * 3.14159

#Area of a circle with a radius of 10
10 * 10 * 3.14159

#Area of a circle with a radius of 11
11 * 11 * 3.14159

If you decide to change the pi to 3.14 instead of 3.14159, you'll need to rewrite everything.

The solution to this problem is a mechanism called ** variables **.

variable

** Variables are like boxes that hold values. You can give this box a name so that you can easily identify what value it contains. This name is called the variable name. ** **

By using a variable, if you want to reuse the value, you can call it just by using the name of the variable.

I will explain how to use variables in order.

Variable declaration and definition

** Creating a variable is called a variable declaration. At this time, give a name to the variable to be created. Then, describing what kind of value to put in the declared variable is called variable definition. ** **

変数.png

Since declaration and definition are basically made at the same time, they are regarded as having the same meaning. Often, I don't really notice the difference, but as a term Let's remember.

The variables are defined as follows: The value on the right side of = </ font> It is an image to put in the variable on the left.

[Example] Ruby file


Variable name=Value to store

[Example] irb


#The contents of the variable pi are the circumference ratio of 3..Defined to be 14159
irb(main):001:0> pi = 3.14159

#When you call pi, the stored 3.14159 is returned
irb(main):002:0> pi
=> 3.14159

#Stored 3 no matter how many times it is executed.14159 is returned
irb(main):003:0> pi
=> 3.14159

In the variable definition, there is a description called ** assignment ** using = </ font>. I will explain about substitution next time.

Summary

** A variable is like a box that holds values. ** **

that's all.

Recommended Posts