在网上浏览关于ruby的互联网时,我看到super
这个词。有人可以说出它是什么以及它能做什么吗?
答案 0 :(得分:3)
super
方法调用父类方法。
例如:
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
如果还不够,那么您可以从here
进一步学习答案 1 :(得分:0)
如果要使用继承,如果要从子类调用父类方法,我们使用super
c2.1.6 :001 > class Parent
2.1.6 :002?> def test
2.1.6 :003?> puts "am in parent class"
2.1.6 :004?> end
2.1.6 :005?> end
=> :test_parent
2.1.6 :006 >
2.1.6 :007 > class Child < Parent
2.1.6 :008?> def test
2.1.6 :009?> super
2.1.6 :010?> end
2.1.6 :011?> end
=> :test_parent
2.1.6 :012 > Child.new.test
am in parent class
=> nil
2.1.6 :013 >
我们可以通过不同的方式使用super(例如:super,super())。
答案 2 :(得分:0)
它用于实现当前方法的超类实现。 在方法体内,调用super就像调用原始方法一样。搜索方法体开始于发现包含原始方法的对象的超类。
database.getConnection()
答案 3 :(得分:0)
Ruby使用super关键字来调用当前方法的超类实现。 在方法体内,调用super就像调用原始方法一样。 搜索方法体在对象的超类中开始,该对象被发现包含原始方法。
def url=(addr)
super (addr.blank? || addr.starts_with?('http')) ? addr : http://#{addr}
end