folderVariables

Introduction

Variables in programming are used to store data. They are like containers that hold information which can be referenced and manipulated throughout the program's execution.

Declaration

To declare variable we have provide it's name and value. Let's assign number 2 to variable called two.
two = 2
Now we can use our variable later in our code. When we provide variabletwo and press enter it will return number 2.
two #=> 2

Data Types

Above we assigned number to our variable but in Ruby we can assign any data type to our variable.
We use method .class to check variable type.
one = 1
one.class #=> Integer

pi = 3.14
pi.class #=> Float

greeting = "Hello"
greeting.class #=> String

is_valid = true
is_valid.class #=> TrueClass
You can also assign result of an expression to your variable.
result = 2 + 3 #=> 5

two = 2
five = 5
seven = two + five #=> 7
In the next chapters you will find more information about data types and methods.

Constants

If you want you can re-assigned your variables values during the program runtime.
greeting = "Hello World!"
greeting #=> "Hello World!

greeting = "Hello Again!"
greeting #=> "Hello Again!"
But in programming there are also consatn variables. These are variables to which you can only assign their value once and cannot change it after that.
To defined constant in Ruby name of this variable must begin with a capital letter, however, by convention, the entire name is usually written in uppercase letters.
PI_NUMBER = 3.14
You can use our constant like normal variable.
PI_NUMBER * 2 # => 6.28
We came to the conclusion that we no longer need such precision and our PI_NUMBER can be equal 3. Let's try to overwrite our constant.
PI_NUMBER = 3
It turns out that our constant is not exactly a constant. Ruby will display warning that we're trying to redefined out constant however it will allow us to do that.
warning: already initialized constant PI_NUMBER
warning: previous definition of PI_NUMBER was here
If we try to use PI_NUMBER now it will have value equal 3.
PI_NUMBER * 3 #=> 9

Naming Conventions

Variable names should always be lowercase, if there are multiple words use underscore to split them. This naming conventions is known assnake_case.
You must remember that you're spending more time on reading code rather than writing it, so remeber that you variables must be as clear as possible.