Ruby: Is it possible to define a class method in a module?

前端 未结 5 1037
萌比男神i
萌比男神i 2020-12-24 00:19

Say there are three classes: A, B & C. I want each class to have a class method, say self.foo, that has exactly the s

5条回答
  •  旧时难觅i
    2020-12-24 00:56

    This is basic ruby mixin functionality that makes ruby so special. While extend turns module methods into class methods, include turns module methods into instance methods in the including/extending class or module.

    module SomeClassMethods
      def a_class_method
        'I´m a class method'
      end
    end
    
    module SomeInstanceMethods
      def an_instance_method
       'I´m an instance method!'
      end
    end
    
    class SomeClass
      include SomeInstanceMethods
      extend SomeClassMethods
    end
    
    instance = SomeClass.new
    instance.an_instance_method => 'I´m an instance method!'
    
    SomeClass.a_class_method => 'I´m a class method'
    

提交回复
热议问题