Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Operators and Expressions
What will this Ruby code print?
class Word
  def initialize(text)
    @text = text
  end
  def +(other)
    @text + " " + other
  end
end
w = Word.new("Hello")
puts w + "World"
AHello World
BHelloWorld
CError: no implicit conversion of String into Word
DHello + World
Step-by-Step Solution
Solution:
  1. Step 1: Understand the + method

    The method concatenates @text, a space, and other.
  2. Step 2: Evaluate the output

    It returns "Hello World" which is printed.
  3. Final Answer:

    Hello World -> Option A
  4. Quick Check:

    String concatenation with + = B [OK]
Quick Trick: Operator methods can combine strings with spaces easily [OK]
Common Mistakes:
  • Expecting no space between words
  • Assuming error due to different types
  • Thinking + always adds numbers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes