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

前端 未结 5 1034
萌比男神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条回答
  •  半阙折子戏
    2020-12-24 01:08

    module Common
      def foo
        puts 'foo'
      end
    end
    
    class A
      extend Common
    end
    
    class B
      extend Common
    end
    
    class C
      extend Common
    end
    
    A.foo
    

    Or, you can extend the classes afterwards:

    class A
    end
    
    class B
    end
    
    class C
    end
    
    [A, B, C].each do |klass|
      klass.extend Common
    end
    

提交回复
热议问题