① What is a variable? (2) Precautions when using Ruby variables
I will briefly explain the above two points.
What is a
a = "tanaka"
b = 20
puts a #The output of the terminal is "tanaka"
puts b #The output of the terminal is "20"
The variable "a" is on the left side of the above "=", and the value "tanaka" is on the right side. The value "tanaka" is assigned to the variable "a". The numerical value "20" is assigned to the variable "b" below it.
Ruby uses "" "(double quotation marks) when entering a string. And since "" "" is not necessary when entering a numerical value, "" "" is removed when entering a numerical value. And below that, I use the puts method to call "a" and "b" to display the values "tanaka" and "20" inside. The operator "=" used here is called the assignment operator.
There are some caveats when using variables.
To put it simply, reserved words are things that cannot be used for variables, constants, etc., things that the word has a role to play.
For example, "if" for bifurcation processing is a reserved word. "Class" for defining a class is also a reserved word. Using these will return an error.
Be aware of this reserved word when defining variables!
List of reserved words
BEGIN class ensure nil self when
END def false not super while
alias defined? for or then yield
and do if redo true __LINE__
begin else in rescue undef __FILE__
break elsif module retry unless __ENCODING__
case end next return until
Reference articles for reserved words https://docs.ruby-lang.org/ja/latest/doc/spec=2flexical.html
It's important to define variables! !! !! !! !!
20 = 20 #It starts with a number, so an error occurs! !! !! !!
_20 = 20 #It starts with an underscore, so it can be defined as a "variable"! !! !! !!
number = 20 #Since it is lowercase, it can be defined as a "variable"! !! !! !! !! !!
Number = 20 #Since it is a capital letter, it is regarded as a "constant"! !! !! !! !! !! !!
Note that variables have naming conventions like this!
A snake case is to start a word with a lowercase letter and connect the connecting parts with "_" (underscore).
Here are some examples.
user_name = "tanaka"
user_age = 20
puts user_name #The output of the terminal is "tanaka"
puts user_age #The output of the terminal is "20"
It is called snake case to put "_" between "user" and "name" which are "user_name". The same is true for "user_age".
Snake case reference article https://wa3.i-3-i.info/word1180.html
-Variables are like boxes for storing values, and variables are defined using the assignment operator "=". ・ Notes on variable definition, do not start with numbers! Start with lowercase letters or _ (underscore)! ・ Add _ (underscore) to connect lowercase letters!
Reference article https://docs.ruby-lang.org/ja/latest/doc/spec=2fvariables.html
Recommended Posts