Calling method in parent class from subclass methods in Ruby
RubyRuby Problem Overview
I've used super
to initialize parent class but I cannot see any way of calling parent class from subclass methods.
I know PHP and other languages do have this feature but cannot find a good way to do this in Ruby.
What would one do in this situation?
Ruby Solutions
Solution 1 - Ruby
If the method is the same name, i.e. you're overriding a method you can simply use super
. Otherwise you can use an alias_method
or a binding.
class Parent
def method
end
end
class Child < Parent
alias_method :parent_method, :method
def method
super
end
def other_method
parent_method
#OR
Parent.instance_method(:method).bind(self).call
end
end
Solution 2 - Ruby
The super
keyword calls a method of the same name in the super class:
class Foo
def foo
"#{self.class}#foo"
end
end
class Bar < Foo
def foo
"Super says: #{super}"
end
end
Foo.new.foo # => "Foo#foo"
Bar.new.foo # => "Super says: Bar#foo"
Solution 3 - Ruby
The super
keyword in Ruby actually calls a method of the same name in the parent class. (source)
class Foo
def foo
# Do something
end
end
class Bar < Foo
def foo
super # Calls foo() method in parent class
end
end
Solution 4 - Ruby
Others have said it already well. Just one additional note of caution:
The syntax super.foo
to call method foo
in the super class is not supported. Rather it will call the super
-method and on the returned result, try to call foo
.
class A
def a
"A::a"
end
end
class B < A
def a
"B::a is calling #{super.a}" # -> undefined method `a` for StringClass
end
end
Solution 5 - Ruby
class Parent
def self.parent_method
"#{self} called parent method"
end
def parent_method
"#{self} called parent method"
end
end
class Child < Parent
def parent_method
# call parent_method as
Parent.parent_method # self.parent_method gets invoked
# call parent_method as
self.class.superclass.parent_method # self.parent_method gets invoked
super # parent_method gets invoked
"#{self} called parent method" # returns "#<Child:0x00556c435773f8> called parent method"
end
end
Child.new.parent_method #This will produce following output
Parent called parent method
Parent called parent method
#<Child:0x00556c435773f8> called parent method
#=> "#<Child:0x00556c435773f8> called parent method"
self.class.superclass == Parent #=> true
Parent.parent_method
and self.class.superclass
will call self.parent_method
(class method) of Parent
while
super
calls the parent_method
(instance method) of Parent
.
Solution 6 - Ruby
As of Ruby 2.2, super_method
can also be used to call super of method a from method b.
method(:a).super_method.call