class Parent
def self.parent_method
"#{self} called parent method"
end
def parent_method
"#{self} called parent method"
end
end
class Child < Parent
def parent_method
# call parent_method as
Parent.parent_method # self.parent_method gets invoked
# call parent_method as
self.class.superclass.parent_method # self.parent_method gets invoked
super # parent_method gets invoked
"#{self} called parent method" # returns "#<Child:0x00556c435773f8> called parent method"
end
end
Child.new.parent_method #This will produce following output
Parent called parent method
Parent called parent method
#<Child:0x00556c435773f8> called parent method
#=> "#<Child:0x00556c435773f8> called parent method"
self.class.superclass == Parent #=> true
Parent.parent_method
và self.class.superclass
sẽ gọi self.parent_method
(phương pháp lớp) của Parent
khi super
gọi (phương pháp chẳng hạn) parent_method
của Parent
.
Nguồn
2018-02-07 08:32:28
Điều này không hiệu quả. 'Child.new.other_method' trả về' NoMethodError: super: không có phương thức superclass 'other_method' cho # '. Lệnh gọi 'super.method()' sẽ chỉ gọi 'phương thức' trên bất kỳ thứ gì được trả về từ lệnh gọi' super' (trong trường hợp này, không tồn tại). 'super' không phải là tham chiếu đến' superclass' của một cá thể. –
Cade
@Xin bạn hoàn toàn chính xác. Tôi đã thực hiện chỉnh sửa cho số này –
Cũng gọi 'super' sẽ gọi siêu với các đối số chính xác đã được chuyển cho phương thức con. Nếu bạn muốn chỉ định các đối số, bạn có thể gọi super với chúng: EG: 'def child (a, b); siêu; end' vs 'def child (a, b); siêu (somevar); end' – Adam