class A def a puts 'in #a' end end class B < A def a b() end def b # here i want to call A#a. end end
Вызов другого метода в суперклассе в рубине
Ответ 1
class B < A
alias :super_a :a
def a
b()
end
def b
super_a()
end
end
Ответ 2
Нет никакого хорошего способа сделать это, но вы можете сделать A.instance_method(:a).bind(self).call
, который будет работать, но уродлив.
Вы даже можете определить свой собственный метод в объекте, чтобы действовать как супер в java:
class SuperProxy
def initialize(obj)
@obj = obj
end
def method_missing(meth, *args, &blk)
@obj.class.superclass.instance_method(meth).bind(@obj).call(*args, &blk)
end
end
class Object
private
def sup
SuperProxy.new(self)
end
end
class A
def a
puts "In A#a"
end
end
class B<A
def a
end
def b
sup.a
end
end
B.new.b # Prints in A#a
Ответ 3
Если вам явно не нужно вызывать A # a из B # b, но нужно позвонить A # a из B # a, что эффективно, что вы делаете с помощью B # b (если только вы не "Пример недостаточно для того, чтобы продемонстрировать, почему вы звоните с B # b, вы можете просто вызвать супер из B # a, как это иногда бывает в методах инициализации. Я знаю, что это очевидно, я просто хотел уточнить для любых новых пользователей Ruby, которые вам не нужны для псевдонима (в частности, это иногда называется" вокруг псевдонима") в каждом случае.
class A
def a
# do stuff for A
end
end
class B < A
def a
# do some stuff specific to B
super
# or use super() if you don't want super to pass on any args that method a might have had
# super/super() can also be called first
# it should be noted that some design patterns call for avoiding this construct
# as it creates a tight coupling between the classes. If you control both
# classes, it not as big a deal, but if the superclass is outside your control
# it could change, w/o you knowing. This is pretty much composition vs inheritance
end
end