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(name) + " and Child"
  end
end

puts Child.new.greet("Alice")
A"Hello, Alice from Child"
B"Hello, Alice from Parent and Child"
C"Hello, Alice from Parent"
DError: wrong number of arguments
Step-by-Step Solution
Solution:
  1. Step 1: Understand method overriding and super call

    The Child#greet method calls super(name), which calls Parent#greet(name) and returns "Hello, Alice from Parent".
  2. Step 2: Concatenate the returned string

    The child method adds " and Child" to the parent's returned string, resulting in "Hello, Alice from Parent and Child".
  3. Final Answer:

    "Hello, Alice from Parent and Child" -> Option B
  4. Quick Check:

    super returns parent's string + child's addition [OK]
Quick Trick: super returns parent's result; child adds more [OK]
Common Mistakes:
  • Thinking super calls child's method again causing recursion
  • Ignoring the concatenation after super call
  • Assuming super without arguments forwards none

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes