Bibek Sharma
Bibek Sharma

Reputation: 3330

difference between calling super and calling super()

What is the difference between calling super and calling super()? Which is the best one if the arguments passed to the child method don’t match what the parent is expecting.

Upvotes: 28

Views: 10542

Answers (3)

Nishi Kant Sharma
Nishi Kant Sharma

Reputation: 35

super equals to super(*args), which brings all args to the inherited method Use super() when you just want to call the method inherited from Parent without passing args

super example:

class Parent
  def say(message)
    p message
  end
end

class Child < Parent
  def say(message)
    super
  end
end

Child.new.say('Hello world!') # => "Hello world!"

super() examples:

class Parent
  def say
    p "I'm the parent"
  end
end

class Child < Parent
  def say(message)
    super
  end
end

Child.new.say('Hello!') # => ArgumentError (wrong number of arguments (given 1, expected 0))


class Parent
  def say
    p "I'm the parent"
  end
end

class Child < Parent
  def say(message)
    super()
  end
end

Child.new.say('Hi!') # => "I'm the parent"

Upvotes: 0

Austio
Austio

Reputation: 6095

Dictates arguments that are sent up the object ancestor chain

super - sends all arguments passed to the function to parent
super() - no arguments
 

Upvotes: 35

Michael Vessia
Michael Vessia

Reputation: 614

When you call super with no arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method with the same name as where you called super from, along with the arguments that were passed to that method.

On the other hand, when called with super(), it sends no arguments to the parent.

If the arguments you have don't match what the parent is expecting, then I would say you would want to use super(), or explicitly list parameters in the functional call to match a valid parent constructor.

Upvotes: 38

Related Questions