A VARIABLE is a NAME for an object. You give an object a name using the ASSIGNMENT operator (it looks like an equal sign).
color = "blue" fruit = "berry"
Anywhere you can use an object, you can use a variable instead.
color + fruit fruit.upcase
Think of memory as a giant warehouse.
If memory is a giant warehouse...
...and objects are boxes in that warehouse
...then a value is the contents of a box
...and a variable is a label you stick on the outside of the box
Which is clearer, this:
60 * 60 * 24
or this:
seconds_per_minute = 60 minutes_per_hour = 60 hours_per_day = 24 seconds_per_day = seconds_per_minute * minutes_per_hour * hours_per_day
?
Let's spend a few minutes just playing around in IRB. Some things to try:
snack = "Apple"
Think of a variable as pointing to an object.
You can assign and reassign variables at will.
color = "blue" fruit = "berry" color + fruit color = "black" color + fruit
Changing a variable (using ASSIGNMENT) just changes the name of an object. It does not change the data inside the object.
fruit = "Apple" snack = fruit
After this both snack
and fruit
...
most messages return new values
fruit = "banana" snack = fruit.upcase
"banana"
and "BANANA"
are two different objects in memory
Most messages do not change the data inside the object.
color.upcase color
But some messages do change the data!
color.upcase! color
This can be dangerous so sometimes those messages end with a BANG (exclamation point).
/
#