What does super. do in ruby?

2019-09-05 12:53发布

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.

标签: ruby super
1条回答
时光不老,我们不散
2楼-- · 2019-09-05 13:27

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
查看更多
登录 后发表回答