What does super.<method-name> do in ruby?

故事扮演 提交于 2019-12-25 01:39:30

问题


With the following code:

class ObjA
    def func
        puts "ObjA"
    end
end

module Mod
    def func
        puts "Mod"
    end
end

class ObjB < ObjA
    include Mod
    def func
        puts "super called"
        super
        puts "super.func called"
        super.func
    end
end

Running ObjB.new.func results in:

ruby-1.9.2-p180 :002 > ObjB.new.func
super called
Mod
super.func called
Mod
NoMethodError: undefined method `func' for nil:NilClass
    from test.rb:19:in `func'
    from (irb):2

I understand what super does - it calls the current method on the superclass. include Mod makes Mod the next superclass so Mod#func is called.

However, what is super.func doing? I thought it would be equivalent to super, but while it does print out the same output, it also throws a NoMethodError.


回答1:


I assume super.func would do the same thing as any form of method chaining. It calls super, and then calls func on the result returned by super.

The super part would call Mod#func, which prints out "Mod", then calls func on the return value of Mod#func, ie nil (that's because puts returns nil). As nil doesn't have a func method, it says

NoMethodError: undefined method `func' for nil:NilClass
    from test.rb:19:in `func'
    from (irb):2


来源:https://stackoverflow.com/questions/6366731/what-does-super-method-name-do-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!