• module 的主要目的是把不同的方法和常量分别放进不同的命名空间。
  • module 的命名方式跟类一样首字母大写,多个单词不用下划线。 如:CircleArea
  • module 语法
      module ModuleName
              ......
      end
  • module用范围解析操作符“::”来调用module中的方法和常量。 如:Math::PI, Math 是module名。
  • 导入模块的方法:
    1. require 'module' -----导入模块。
        如:require 'date', 导入Date模块,但是不是require 'Date'
        调用module中的方法和常量时用模块名和范围解析操作符,如Math::PI

    2. include 模块名, 如include Math
        调用模块中的方法和常量时不需要写模块名和范围解析操作符,直接调用。如:cos(), 而不需要写Math::cos()
  • 可以把module看成是一个不能实例化,不能继承的类,它可以和类一起模拟实现多重继承

    module MartialArts
      def swordsman
      puts "I'm a swordsman."
      end
    end

    class Ninja
      include MartialArts
      def initialize(clan)
        @clan = clan
      end
    end

    class Samurai
      include MartialArts
      def initialize(shogun)
        @shogun = shogun
      end
    end

  • include关键字让实例可以使用模型中的方法和常量,extend关键字则可以让类自身使用模型中的方法和常量

    module ThePresent
      def now
        puts "It's #{Time.new.hour > 12 ? Time.new.hour - 12 : Time.new.hour}:#{Time.new.min} #{Time.new.hour > 12 ? 'PM' : 'AM'} (GMT)."
      end
    end

    class TheHereAnd
      extend ThePresent
    end

    TheHereAnd.now

posted on 2015-03-31 19:50  cainiaozhang  阅读(376)  评论(2编辑  收藏  举报