Challenge - 5 Problems
Ruby String Concatenation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code?
Consider the following Ruby code snippet. What will be printed when it runs?
Ruby
str = "Hello" str << " World" puts str
Attempts:
2 left
💡 Hint
The << operator appends the string on the right to the string on the left with a space if included.
✗ Incorrect
The << operator appends the exact string on the right to the string on the left without adding extra spaces. Since " World" includes a space at the start, the output is "Hello World".
❓ Predict Output
intermediate2:00remaining
What does this code print?
What will be the output of this Ruby code?
Ruby
a = "foo" b = a b << "bar" puts a
Attempts:
2 left
💡 Hint
Remember that << modifies the original string in place.
✗ Incorrect
Both a and b point to the same string object. Using << on b modifies that object, so a also reflects the change.
🔧 Debug
advanced2:00remaining
Why does this code raise an error?
This Ruby code raises an error. What is the cause?
Ruby
str = nil str << "test"
Attempts:
2 left
💡 Hint
Check what methods nil supports.
✗ Incorrect
nil in Ruby does not have the << method, so calling str << "test" when str is nil raises NoMethodError.
🧠 Conceptual
advanced2:00remaining
What is the difference between + and << for strings in Ruby?
Choose the correct statement about the difference between + and << when used with strings in Ruby.
Attempts:
2 left
💡 Hint
Think about whether the original string changes after using + or <<.
✗ Incorrect
The + operator returns a new string without changing the original, while << appends to the original string modifying it.
❓ Predict Output
expert3:00remaining
What is the final output of this Ruby code?
Analyze the following Ruby code and determine what it prints.
Ruby
str1 = "abc" str2 = str1 str1 += "def" str2 << "xyz" puts str1 puts str2
Attempts:
2 left
💡 Hint
Remember that += creates a new string object, while << modifies the original.
✗ Incorrect
str1 += "def" creates a new string object for str1, so str2 still points to the original "abc". Then str2 << "xyz" modifies that original string. So str1 is "abcdef" and str2 is "abcxyz".