Variables – naming things
A variable is a name for a value. You assign it with =. Variable names are lowercase, with underscores: favorite_food, bacon_strips.
food = "bacon"
amount = 3
foodThe cells of a lesson share their memory – like in a real notebook. You can reuse the variable amount from above here. (Getting an error? Run the cell above first.)
amount * 2A variable can get a new value at any time. amount = amount + 1 looks odd to a mathematician – but in Ruby = does not mean “is equal to”, it means “gets the value”: the right side is computed first, then the result lands in the variable on the left. There's a shorthand for it, too: +=.
amount = amount + 1
amount += 10
amountRun the cell a second time – what happens? Every run keeps computing with the value amount has right now. In the same way there are -=, *= and /=.
Every value belongs to a class – that's what Ruby calls its kind. .class tells you which: text is a String, whole numbers are Integers, decimal numbers Floats. You convert with to_s (to text), to_i (to a whole number) and to_f (to a decimal number):
puts food.class
puts amount.class
puts 3.5.class
"42".to_i + 8Why this matters: "42" is text, not a number – so "42" + 8 doesn't work. What Ruby says about it, and how to read such messages, is shown in lesson 28.
Two variables at once? That works too: width, height = 4, 3 gives width the value 4 and height the value 3.
And a few rules for names: they start with a lowercase letter or _, never with a digit, and contain no spaces. Case matters: amount and Amount are two different names – and a name with a capital first letter is even something else in Ruby, a constant. Good names are half the battle: price_in_francs tells you far more than p or x.
name with your name (a string) and age with a number.# name = ...
# age = ...
a and b, so that afterwards a is 2 and b is 1 – with a third variable as temporary storage. Finally work out total = a + b.a = 1
b = 2
# swap a and b - with a helper variable
# total = ... # a plus b