2014-12-01 78 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