2014-12-01 56 views
0

比方说,我有一个一流的,我想能够调用类本身这个类的一个实例相同的方法:创建两者功能类和实例方法的方法

class Foo 
    def self.bar 
    puts 'hey this worked' 
    end 
end 

这让我做到以下几点:

Foo.bar #=> hey this worked 

但我也希望能够做到:

Foo.new.bar #=> NoMethodError: undefined method `bar' for #<Foo:0x007fca00945120> 

所以现在我修改我的同班同学有bar实例方法:

class Foo 
    def bar 
    puts 'hey this worked' 
    end 
end 

现在我可以调用这两个类酒吧和类的一个实例:

Foo.bar #=> hey this worked 
Foo.new.bar #=> hey this worked 

现在我的班Foo是'湿':

class Foo 
    def self.bar 
    puts 'hey this worked' 
    end 

    def bar 
    puts 'hey this worked' 
    end 
end 

有没有办法避免这种冗余?

回答

2

有一个方法调用另一个。否则,不,没有办法避免这种“冗余”,因为没有冗余。有两个独立的方法碰巧具有相同的名称。

class Foo 
    def self.bar 
    puts 'hey this worked' 
    end 

    def bar 
    Foo.bar 
    end 
end