Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - String Operations
What will be the output of the following Ruby code?
text = "hello hello hello"
result = text.sub('hello', 'hi')
puts result
Ahi hello hello
Bhello hi hello
Chi hi hi
Dhello hello hi
Step-by-Step Solution
Solution:
  1. Step 1: Understand what sub does here

    sub replaces only the first occurrence of 'hello' with 'hi'.
  2. Step 2: Apply replacement to the string

    The first 'hello' becomes 'hi', the rest remain unchanged, so the string becomes "hi hello hello".
  3. Final Answer:

    hi hello hello -> Option A
  4. Quick Check:

    sub replaces first match only [OK]
Quick Trick: sub changes only first match, others stay same [OK]
Common Mistakes:
MISTAKES
  • Thinking sub replaces all matches
  • Confusing output with gsub behavior
  • Misreading the string content

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes