Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Inheritance
What will be the output of this Ruby code?
class Parent
  def greet(name)
    "Hello, #{name} from Parent"
  end
end

class Child < Parent
  def greet(name)
    super + " and Child"
  end
end

puts Child.new.greet("Alice")
AHello, Alice from Parent and Child
BHello, Alice from Child
CHello, from Parent and Child
DError: wrong number of arguments
Step-by-Step Solution
Solution:
  1. Step 1: Trace the method call in Child#greet

    The Child's greet method calls super without parentheses, so it passes the argument "Alice" to Parent#greet. Parent#greet returns "Hello, Alice from Parent". Child appends " and Child" to this string.
  2. Final Answer:

    Hello, Alice from Parent and Child -> Option A
  3. Quick Check:

    super passes args, output combines strings [OK]
Quick Trick: super without () passes all args automatically [OK]
Common Mistakes:
  • Assuming super passes no arguments by default
  • Expecting an error due to argument mismatch
  • Ignoring the appended string in Child method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes