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
有沒有辦法避免這種冗餘?