9

初心者の質問:

インクルードと拡張がどのように機能するかは知っていますが、単一のモジュールからクラス メソッドとインスタンス メソッドの両方を取得する方法があるかどうか疑問に思っています。

これは私が2つのモジュールでそれを行う方法です:

module InstanceMethods
    def mod1
        "mod1"
    end
end

module ClassMethods
    def mod2
        "mod2"
    end
end

class Testing
    include InstanceMethods
    extend ClassMethods 
end

t = Testing.new
puts t.mod1
puts Testing::mod2

お時間を割いていただきありがとうございます...

4

3 に答える 3

3

はい。Ruby の天才のおかげで、それはあなたが期待するのとまったく同じくらい簡単です。

module Methods
    def mod
        "mod"
    end
end

class Testing
    include Methods # will add mod as an instance method
    extend Methods # will add mod as a class method
end

t = Testing.new
puts t.mod
puts Testing::mod

または、次のようにすることもできます。

module Methods
    def mod1
        "mod1"
    end

    def mod2
        "mod2"
    end
end

class Testing
    include Methods # will add both mod1 and mod2 as instance methods
    extend Methods # will add both mod1 and mod2 as class methods
end

t = Testing.new
puts t.mod1
puts Testing::mod2
# But then you'd also get
puts t.mod2
puts Testing::mod1
于 2017-11-27T11:50:23.817 に答える