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?
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.
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.
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.
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).
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.
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’
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With