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
有没有办法避免这种冗余?