0
0
Rubyprogramming~20 mins

Super keyword behavior in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Super Keyword Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of super with arguments in method override
What is the output of the following Ruby code?
Ruby
class Parent
  def greet(name)
    "Hello, #{name}!"
  end
end

class Child < Parent
  def greet(name)
    super(name).upcase
  end
end

puts Child.new.greet("Alice")
AError: wrong number of arguments
BHello, Alice!
Chello, alice!
DHELLO, ALICE!
Attempts:
2 left
💡 Hint
Remember that super(name) calls the parent method with the same argument, then upcase converts the string to uppercase.
Predict Output
intermediate
2:00remaining
Effect of super without arguments in method override
What will this Ruby code print?
Ruby
class A
  def info(x)
    "Value: #{x}"
  end
end

class B < A
  def info(x)
    super + "!"
  end
end

puts B.new.info(5)
AValue: 5!
BValue: !
CError: wrong number of arguments
DValue: 5
Attempts:
2 left
💡 Hint
Calling super without arguments passes the same arguments received by the method.
Predict Output
advanced
2:00remaining
super with block forwarding behavior
What is the output of this Ruby code?
Ruby
class Base
  def process
    yield if block_given?
  end
end

class Derived < Base
  def process
    super { puts "Inside block" }
  end
end

Derived.new.process
ANo output
BInside block
CError: no block given
DError: wrong number of arguments
Attempts:
2 left
💡 Hint
super forwards the block given to it, so the block inside super is executed.
Predict Output
advanced
2:00remaining
super with no arguments and no block in method with parameters
What happens when this Ruby code runs?
Ruby
class Parent
  def calculate(a, b)
    a + b
  end
end

class Child < Parent
  def calculate(a, b)
    super * 2
  end
end

puts Child.new.calculate(3, 4)
AError: wrong number of arguments
B7
C14
DError: undefined method '*' for nil
Attempts:
2 left
💡 Hint
super without parentheses passes all arguments received by the method.
Predict Output
expert
3:00remaining
super in multiple inheritance levels with keyword arguments
What is the output of this Ruby code?
Ruby
class Alpha
  def info(x:, y:)
    "Alpha: x=#{x}, y=#{y}"
  end
end

class Beta < Alpha
  def info(x:, y:)
    super(x: x + 1, y: y + 1) + " -> Beta"
  end
end

class Gamma < Beta
  def info(x:, y:)
    super(x: x * 2, y: y * 2) + " -> Gamma"
  end
end

puts Gamma.new.info(x: 1, y: 2)
AAlpha: x=3, y=5 -> Beta -> Gamma
BAlpha: x=2, y=3 -> Beta -> Gamma
CAlpha: x=4, y=6 -> Beta -> Gamma
DError: wrong number of arguments
Attempts:
2 left
💡 Hint
Each super call modifies the keyword arguments before passing them up the chain.