Bird
0
0

What will happen when the following Ruby code runs?

medium📝 Predict Output Q13 of 15
Ruby - String Operations
What will happen when the following Ruby code runs?
str = "hello".freeze
str << " world"
AThe string becomes "hello world".
BThe string remains "hello" silently.
CThe string changes to " world".
DA runtime error occurs: can't modify frozen String.
Step-by-Step Solution
Solution:
  1. Step 1: Understand string freezing effect

    Freezing the string "hello" makes it immutable, so any modification attempt will raise an error.
  2. Step 2: Analyze the << operation

    The << operator tries to append " world" to the frozen string, which is not allowed and causes a runtime error.
  3. Final Answer:

    A runtime error occurs: can't modify frozen String. -> Option D
  4. Quick Check:

    Modifying frozen string = error C [OK]
Quick Trick: Appending to frozen string causes error [OK]
Common Mistakes:
  • Assuming string changes silently
  • Thinking string resets to new value
  • Believing no error occurs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes