Definition:
- A name on the left side of the assignment operator = is assigned to the object on the right side.
- A variable itself is not a “thing”. It’s just a name for a thing (an object).
- You can pick whatever variable names you want, they’re just names, like post-it notes stuck onto actual objects.
number = 1
puts number
a = 1
puts a
large_number = 1
puts large_number
apples = 1
puts apples
Reusing variable names:
- Variable names can be re-used, and re-assigned.
- Using variable names can be useful to break up long lines and make code more expressive and readable.
- There are spaces around the assignment operator
=
as well as the arithmetical operators+
and*
.
number = 4 #On the first line Ruby creates the number (object) 4.
number = (number * 3) #on the second line, Ruby first looks at the stuff on the right side, and evaluates the expression number * 3. Doing so it will create the number (object) 3 and multiply it with the object that currently has the name number, which is 4. This operation results in a new number (object) 12
puts number + 2 #On the third line Ruby will, again, first look at the expression number + 2 on the right. It creates the object 2 and adds it to the object that currently has the name number. This results in a new number (object) 14.
#Finally Ruby passes this object 14 to puts, which outputs it to the screen.
Things on the right go first:
Ruby evaluates the expression on the right first.
number = 2 + 3 * 4
puts number
number = 3 * 6 + 2
puts number
Top comments (0)