Challenge - 5 Problems
Heredoc Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple heredoc string
What is the output of this Ruby code using heredoc syntax?
Ruby
str = <<-TEXT
Hello,
World!
TEXT
puts strAttempts:
2 left
💡 Hint
Remember that heredoc preserves newlines exactly as written.
✗ Incorrect
The heredoc syntax preserves the line breaks and includes a final newline. So the output includes both lines and ends with a newline.
❓ Predict Output
intermediate2:00remaining
Indentation behavior with <<- heredoc
What will this Ruby code print?
Ruby
str = <<-DOC
Line one
Line two
DOC
puts strAttempts:
2 left
💡 Hint
The <<- syntax allows the end marker to be indented but does not remove indentation inside the string.
✗ Incorrect
The indentation inside the heredoc content is preserved exactly, so the two lines start with two spaces each.
❓ Predict Output
advanced2:00remaining
Difference between <<- and <<~ in heredoc
What is the output of this Ruby code?
Ruby
str = <<~HEREDOC
Hello
World
HEREDOC
puts strAttempts:
2 left
💡 Hint
The <<~ syntax removes the least common leading whitespace from all lines.
✗ Incorrect
The <<~ removes the smallest indentation common to all lines, so the first line's 4 spaces are removed from both lines, preserving relative indentation.
🧠 Conceptual
advanced2:00remaining
Heredoc with variable interpolation
Given this Ruby code, what will be the output?
Ruby
name = "Alice" str = <<-TEXT Hello, #{name}! Welcome. TEXT puts str
Attempts:
2 left
💡 Hint
Double-quoted heredocs allow variable interpolation.
✗ Incorrect
The heredoc with <<- uses double quotes by default, so #{name} is replaced with Alice.
🔧 Debug
expert3:00remaining
Why does this heredoc cause a syntax error?
This Ruby code raises a SyntaxError. What is the cause?
Ruby
str = <<HEREDOC
Hello
World
HEREDOC
puts strAttempts:
2 left
💡 Hint
Check the position of the ending marker when using << without a dash.
✗ Incorrect
When using <