Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Super keyword in Ruby

Tags:

ruby

What is the super for in this code?

def initialize options = {}, &block   @filter = options.delete(:filter) || 1   super end 

As far as I know it's like calling the function recursively, right?

like image 538
mabounassif Avatar asked Jan 08 '11 03:01

mabounassif


People also ask

What is super () is used for?

The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.

What is difference between super and super () in Ruby?

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.

Why we use super in rails?

The function super is used to invoke the original method, searching of the method body starts in the super class of the object that was found to contain the original method.

What is * args in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).


2 Answers

no... super calls the method of the parent class, if it exists. Also, as @EnabrenTane pointed out, it passes all the arguments to the parent class method as well.

like image 123
sethvargo Avatar answered Oct 21 '22 03:10

sethvargo


super calls a parent method of the same name, with the same arguments. It's very useful to use for inherited classes.

Here's an example:

class Foo   def baz(str)     p 'parent with ' + str   end end  class Bar < Foo   def baz(str)     super     p 'child with ' + str   end end  Bar.new.baz('test') # => 'parent with test' \ 'child with test' 

There's no limit to how many times you can call super, so it's possible to use it with multiple inherited classes, like this:

class Foo   def gazonk(str)     p 'parent with ' + str   end end  class Bar < Foo   def gazonk(str)     super     p 'child with ' + str   end end  class Baz < Bar   def gazonk(str)     super     p 'grandchild with ' + str   end end  Baz.new.gazonk('test') # => 'parent with test' \ 'child with test' \ 'grandchild with test' 

If there's no parent method of the same name, however, Ruby raises an exception:

class Foo; end  class Bar < Foo   def baz(str)     super     p 'child with ' + str   end end  Bar.new.baz('test') # => NoMethodError: super: no superclass method ‘baz’ 
like image 35
vonconrad Avatar answered Oct 21 '22 02:10

vonconrad