About class

在ruby中经常可以见到这样的写法:

class A
  class << self
     def hello
        puts "hello"
     end
   end
end

这样的写法和

class A
  def self.hello
     puts "hello"
   end
end

可以说是完全一样的。第一种写法的一个好处是,如果需要在一个class或者module里面定义多个类级别的方法, 这种写法可以少写很多个"self." :)

还有一个好处是,可以使用attr_reader/attr_accessor 之类的meta programming的method.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章