ruby · level 1 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put any value inside a string with #{}.
Joining with + gets fiddly. Instead, write #{} inside a string and put a value between the curly brackets. Ruby swaps in the value for you. This is called , and it only works with double quotes.
Sometimes you need to a value, changing it from one kind to another. .to_i turns a string into an integer, so "7".to_i is 7. .to_s turns a number into a string.
gets always hands back a string, even when someone types a number. To do maths with the answer, convert it: age = gets.chomp.to_i.
name = "Mia"
age = 9
puts "#{name} is #{age} years old."
puts "Next year, #{name} will be #{age + 1}."
puts "7".to_i + 3
puts "Score: " + 10.to_s Ruby works out anything inside #{}, even sums like #{age + 1}.
guess first
Maths inside a string? Guess what shows.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
apples = 3
puts "I have #{apples * 2} apples."
your turn
Your turn. Jump into the future.
In the blank, type how many years to jump into the future, as a number. We will answer the question with 12.
fix it
Grandad's birthday maths has crashed. Fix it!
- Read the error. It is a TypeError on line 3. What kind of value does
getshand back? - age holds the string "76", and Ruby cannot add 1 to a string. Convert it first.
- Change line 2 to age = gets.chomp.to_i, then press run.
nailed it
your strings can hold anything now. :D
#{}drops a value into a double-quoted string..to_imakes an integer..to_smakes a string.- Convert
getsanswers before doing maths with them.
new words in your collection
- interpolation
- convert
This lesson isn’t saved. A free account remembers every lesson you finish.