Variables
IRB: As soon as you hit Enter and the Ruby command has finished executing, the result is forgotten
We should be able to use the result of one line in the next
Enter variables!
You can think of variables like drawers in an apothecary
The drawers each have a label on them and they contain a specific thing at any time (or nothing)
my_string = "Hello world"
a_number = 5 + 2
my_string = "Hello world"
a_number = 5 + 2
=is called the assignment operator
=differs from how it's used in mathematics
variable_name = expression
5
"Hello world"
a_number.odd?
my_string.include?("Hello")
8 * 6
(a_number / 5.0) + 42
An expression is any piece of Ruby code that returns a value
Any expression can be assigned to a variable!
b_number = (a_number / 5.0) + 42
You can give existing variables a new value by reassigning
a_number = 5 + 2
a_number = 42
Note: Note syntax is the same as for assignment
Note: The old value of the variable is lost by doing this
You can also use the variable in an expression when reassigning it
a_number = 5 + 2
a_number = a_number + 3
Note: Here's where it definitely stops making sense mathematically ;-)
A variable always has a specific type
For example String or Integer
Whenever Ruby executes a method on a variable, it first checks the type!
a_number = 5 + 2
a_number.length
NoMethodError (undefined method `length' for 7:Integer)
Which of these are good variable names?
mynewvariable user_name date_of_birth 5_things AnotherVariableName list_of_favourite_drinks
These characters are allowed:
a - z)
0 - 9)
_)
_instead)
Variable names can't start with a digit
What questions do you have?