Variable in Ruby
The variable is where we can store some value to perform a manipulation.
Considering that we have 99 chocolates, we want to divide it by 9 to find out how many people will receive each chocolate.
total_cho = 99
=> 99
person = 9
=> 9
each_person = 99/9
=> 11
Naming Convention:
There is no space between the variables.
There is no special character expect _(underscore). eg each_person
A variable name can have a number but a variable can not start with the number.
The capital character should not appear at the start of the variable.
fruit = "banana"
=> "banana"
fruit123 = "apple"
=> "apple"
fruitType = "summer seasonal"
=> "summer seasonal"
_fruit = "kiwi"
=> "kiwi"
The underscore — a special variable:
If you want to use the last manipulate output so with the help of underscore we can use it.
data = 798
=> 798
3.0.0 :014 > data += 4569
=> 5367
3.0.0 :015 > value = _
=> 5367
Constants:
A constant can be thought of as a variable whose value doesn’t change. Constant in Ruby start with a capital letter.
Pi = 3.14
=> 3.14
r = 3
=> 3
Pi*r**2
=> 28.26
Pi = 3.14
(irb):24: warning: already initialized constant Pi
(irb):21: warning: previous definition of Pi was here
=> 3.14