0
0
Rubyprogramming~20 mins

Heredoc syntax for multiline strings in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Heredoc Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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 str
AHello,\nWorld!\n
BHello, World!
CHello,\nWorld!
DHello,World!\n
Attempts:
2 left
💡 Hint
Remember that heredoc preserves newlines exactly as written.
Predict Output
intermediate
2:00remaining
Indentation behavior with <<- heredoc
What will this Ruby code print?
Ruby
str = <<-DOC
  Line one
  Line two
DOC
puts str
A Line one\n Line two\n
BLine one\nLine two\n
Cowt eniL eno eniL
D Line one Line two
Attempts:
2 left
💡 Hint
The <<- syntax allows the end marker to be indented but does not remove indentation inside the string.
Predict Output
advanced
2:00remaining
Difference between <<- and <<~ in heredoc
What is the output of this Ruby code?
Ruby
str = <<~HEREDOC
    Hello
      World
  HEREDOC
puts str
AHello\nWorld\n
B Hello\n World\n
CHello\n World\n
D Hello\n World\n"
Attempts:
2 left
💡 Hint
The <<~ syntax removes the least common leading whitespace from all lines.
🧠 Conceptual
advanced
2: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
AHello, #{name}!\nWelcome.\n
BHello, \#{name}!\nWelcome.\n
CHello, Alice! Welcome.
DHello, Alice!\nWelcome.\n
Attempts:
2 left
💡 Hint
Double-quoted heredocs allow variable interpolation.
🔧 Debug
expert
3: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 str
AThe heredoc content must be indented to match the ending marker.
BThe ending HEREDOC marker is indented, but << without a dash requires it to be at the start of the line.
CThe heredoc content must not contain blank lines.
DThe heredoc marker must be quoted to avoid errors.
Attempts:
2 left
💡 Hint
Check the position of the ending marker when using << without a dash.