2012-03-01 55 views
0

我有以下模塊:的Ruby模塊方法無障礙

module Foo 
    def f1 x 
    puts "f1(#{x})" 
    end 
    def Foo.f2 x 
    puts "f2(#{x})" 
    end 
end 

當它被納入一類:

class Bar 
    include Foo 

    Foo.f2 "bar" # This works 
    f1 "bar"  # Missing method 

    def b x 
     f1 x  # This works too 
    end 
end 

爲什麼是F1在兩種情況下不同的行爲?

模塊metod的範圍是如何定義的?

可以用這種方式寫入f1,它可以像f1 "bar"那樣工作嗎?比如說Rakefile中的task

回答

1

如果您想要將類方法添加到Bar,您希望使用included;見Yehuda's post on the subject。它取決於(某種程度上)你實際上想要做什麼。