Ruby Module Method Access

前端 未结 3 1987
野的像风
野的像风 2021-01-31 17:01

I have a ruby module for constants. It has a list of variables and 1 method which applies formatting. I can\'t seem to access the method in this module. Any idea why?

3条回答
  •  终归单人心
    2021-01-31 17:54

    If you include the module the method becomes an instance method but if you extend the module then it becomes a class method.

    module Const
      def format
        puts 'Done!'
      end
    end
    
    class Car
      include Const
    end
    
    Car.new.format # Done!
    Car.format # NoMethodError: undefined method format for Car:Class
    
    class Bus
      extend Const
    end
    
    Bus.format # Done!
    Bus.new.format # NoMethodError: undefined method format
    

提交回复
热议问题