Reprinted from Blog Article.
You can use super
to call a parent method with the same name as itself.
def value
"Super#value"
end
end
class Sub < Super
def value
# Super#Call value
super
end
end
p Sub.new.value
# => "Super#value"
So what if you want to call an arbitrary parent method from a different method?
class Super
def value
"Super#value"
end
end
class Sub < Super
def value
"Sub#value"
end
def value2
#Here Super#I want to call value
end
end
Method # super_method
In this case you can use Method # super_method
.
Get any method object as follows, and get the parent method object with #super_method
.
class Super
def value
"Super#value"
end
end
class Sub < Super
def value
"Sub#value"
end
def value2
#Get a method object of value and reference its parent method
method(:value).super_method.call
end
end
p Sub.new.value2
# => "Super#value"
You can also use .instance_method
to call a method of any class as shown below.
class Super
def value
"Super#value"
end
end
class Sub < Super
def value
"Sub#value"
end
def value2
Super.instance_method(:value).bind(self).call
end
end
p Sub.new.value2
# => "Super#value"
Recommended Posts