你如何更喜欢在Ruby中定义类方法?

前端之家收集整理的这篇文章主要介绍了你如何更喜欢在Ruby中定义类方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
John Nunemaker最近在Ruby上发表了关于 various ways to define class methods文章,给出了这三个选择: @H_403_2@# Way 1 class Foo def self.bar puts 'class method' end end # Way 2 class Foo class << self def bar puts 'class method' end end end # Way 3 class Foo; end def Foo.bar puts 'class method' end

>你最喜欢做什么?
你喜欢上述以外的东西吗?
>如果你使用多种方式,你在什么情况下使用它们?

解决方法

我一直用方式1: @H_403_2@class Foo def self.bar puts 'class method' end end

它不是冗长的,它将该方法保留在类的相同上下文中.

猜你在找的Ruby相关文章