zoukankan      html  css  js  c++  java
  • Ruby module ---模块,组件

    • 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

  • 相关阅读:
    使用PyDNS查询
    C#结构体
    使用CreateProcess函数运行其他程序
    运算符重载
    C#学习抽象类和方法
    sed命令使用
    Python For Delphi 示例
    建立Socket
    使用 lambda 函数
    C#接口实现
  • 原文地址:https://www.cnblogs.com/patientAndPersist/p/4381851.html
Copyright © 2011-2022 走看看