ruby · level 2 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A holds many lines of text in one string.
Every line of text ends with an invisible character. Inside double quotes you can write it as \n, so "one\ntwo" is two lines.
For longer text, use a heredoc. Start with <<~ and a word in capitals, write your lines, then put the same word on its own line to close it. The ~ removes the spaces at the start of each line.
.lines cuts a string into an array of lines, each keeping its newline. .each_line loops over them, and .chomp bites each newline off.
puts "Ready\nSteady\nGo!"
poem = <<~TEXT
Roses are red
Violets are blue
TEXT
p poem.lines.length
poem.each_line do |line|
puts line.chomp.upcase
end Pick a closing word that never appears in your text, like TEXT or POEM.
guess first
Count the lines. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
list = <<~LIST
bread
milk
eggs
LIST
puts list.lines.length
puts list.lines.last.chomp.length
your turn
Your turn. Number a to-do list.
Write three jobs in the heredoc, one on each line, then press run to see them numbered.
fix it
Every sentence snaps in two. Can you fix it?
- Each sentence breaks in two, and every count is one too big. What is hiding at the end of each line?
- Each line keeps its newline. It counts as a character, and it breaks the sentence.
- Add name = item.chomp inside the loop, then use name instead of item on the puts line.
nailed it
your strings can span many lines. :D
\nis the newline character inside double quotes.- A heredoc starts with
<<~WORDand ends withWORD. .chompeach line from.linesor.each_line.
new words in your collection
- newline
- heredoc
This lesson isn’t saved. A free account remembers every lesson you finish.