Ruby Class Methods vs. Methods in Eigenclasses

前端 未结 4 990
伪装坚强ぢ
伪装坚强ぢ 2021-02-19 08:17

Are class methods and methods in the eigenclass (or metaclass) of that class just two ways to define one thing?

Otherwise, what are the differences?

cla         


        
4条回答
  •  名媛妹妹
    2021-02-19 08:21

    In Ruby there really are no such things as class methods. Since everything is an object in Ruby (including classes), when you say def self.class_method, you are just really defining a singleton method on the instance of the class Class. So to answer your question, saying

    class X
      def self.a
        puts "Hi"
      end
    
      class << self
        def b
          puts "there"
        end
      end
    end
    
    X.a # => Hi
    X.b # => there
    

    is two ways of saying the same thing. Both these methods are just singeton (eigen, meta, ghost, or whatever you want to call them) methods defined in the instance of your Class object, which in your example was X. This topic is part of metaprogramming, which is a fun topic, that if you have been using Ruby for a while, you should check out. The Pragmatic Programmers have a great book on metaprogramming that you should definitely take a look at if you interested in the topic.

提交回复
热议问题