класс A def a помещает 'в #a' end endкласс B < A def a b() end def b
здесь я хочу вызвать A#a.
end end
Красивого способа сделать это нет, но вы можете сделать A.instance_method(:a).bind(self).call
, что будет работать, но некрасиво.
Вы даже можете определить свой собственный метод в Object, чтобы действовать как super в 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
Если вам не нужно явно вызывать A#a из B#b, а нужно вызвать A#a из B#a, что, по сути, вы и делаете через B#b (если только ваш пример не достаточно полный, чтобы продемонстрировать, почему вы вызываете из B#b, вы можете просто вызвать super из B#a, как это иногда делается в методах initialize. Я знаю, что это очевидно, но я просто хотел уточнить для новичков в 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's 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