Is it possible to call parent method specifying method name explicitly
like super.foobar() or parent::foobar()?
class Parent
def hello(name)
puts "Hello #{name}!"
end
end
class Child
def hello(name)
# ...
_hello(name)
# ...
end
private
def _hello(name)
# ...
super(name) # want to call Parent#hello(), not _hello()
# ...
end
end
class Child < Parent
Parent.instance_method(:hello).bind(self).call(*args)
end
def _hello(name)
parent_hello(name)
end
end
Folks, why are you making this so complicated? Nobody mentions the
standard way of doing this by using “super”:
class Parent
def hello_same_args(a)
puts a
end
def hello_different_args
puts “We don’t need args”
end
end
class Child < Parent
def hello_same_args(a)
super
puts “now in child”
end
def hello_different_args(x)
super()
puts “Child got #{x}”
end
end
irb(main):022:0> Child.new.hello_same_args “ARG”
ARG
now in child
=> nil
irb(main):023:0> Child.new.hello_different_args “ARG”
We don’t need args
Child got ARG
=> nil
Only if you want to call a different method in the super class you
need to use one of the other approaches. But if you think about it,
usually this is not needed.
It’s ugly but this works (i assume Child subclasses Parent?)
class Child < Parent
def _hello(name)
Parent.instance_method(:hello).bind(self).call(name)
end
end
makoto kuwata wrote in post #983231:
Is it possible to call parent method specifying method name explicitly
like super.foobar() or parent::foobar()?
class Parent
def hello(name)
puts "Hello #{name}!"
end
end
class Child
def hello(name)
# ...
_hello(name)
# ...
end
private
def _hello(name)
# ...
super(name) # want to call Parent#hello(), not _hello()
# ...
end
end
Folks, why are you making this so complicated? Nobody mentions the
standard way of doing this by using “super”:
[…]
Only if you want to call a different method in the super class you
need to use one of the other approaches. But if you think about it,
usually this is not needed.
The original poster specifically asked about calling a different
method in the parent that was also redefined in the child,
which is why I didn’t show the use of super. From the original
message:
super(name) # want to call Parent#hello(), not _hello()
The original poster specifically asked about calling a different
method in the parent that was also redefined in the child,
which is why I didn’t show the use of super. From the original
message:
super(name) # want to call Parent#hello(), not _hello()
Ah, that was the piece I missed. Sorry for the noise.
I’d still question the wisdom of such a design though.
Kind regards
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.