2012-03-01 56 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。它取决于(某种程度上)你实际上想要做什么。