in ruby what's the difference between self.method and a method within class << self

后端 未结 2 1351
暖寄归人
暖寄归人 2021-02-05 17:25
class Foo

  def self.one; 1 end

  class << self
    def two; 2 end
  end

end
puts Foo.singleton_methods.inspect # => [\"two\", \"one\"]

I\'

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 17:46

    I strongly recommend you to read "Metaprogramming Ruby". This book explains about Ruby's object model, including singleton method and singleton class.

    http://pragprog.com/titles/ppmetr/metaprogramming-ruby

    This article also explains same topic.

    http://www.contextualdevelopment.com/articles/2008/ruby-singleton

提交回复
热议问题