Bird
0
0

Given this code, what will Child.new.greet output?

hard📝 Application Q15 of 15
Ruby - Inheritance
Given this code, what will Child.new.greet output?
class Parent
  def greet(name = "Guest")
    "Hello, #{name} from Parent"
  end
end

class Child < Parent
  def greet(name = nil)
    if name
      super(name.upcase)
    else
      super()
    end
  end
end

puts Child.new.greet
puts Child.new.greet("alice")
AHello, from Parent Hello, alice from Parent
BHello, Guest from Parent Hello, ALICE from Parent
CHello, Guest from Parent Hello, alice from Parent
DError due to wrong arguments in super calls
Step-by-Step Solution
Solution:
  1. Step 1: Analyze Child#greet with no argument

    When called without argument, name is nil, so super() calls Parent#greet with no arguments, using default "Guest". When called with "alice", name.upcase is "ALICE" passed to super(name.upcase), so Parent#greet returns "Hello, ALICE from Parent".
  2. Final Answer:

    Hello, Guest from Parent Hello, ALICE from Parent -> Option B
  3. Quick Check:

    super() calls parent with defaults; super(args) passes modified args [OK]
Quick Trick: Use super() for no args, super(args) to pass specific args [OK]
Common Mistakes:
  • Assuming super() passes current args
  • Ignoring default parameter in Parent#greet
  • Not uppercasing the argument before passing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes