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

  • 相关阅读:
    python运行出现TypeError: super() takes at least 1 argument (0 given)错误
    史上最全Python数据分析学习路径图
    Windows平台Python编程必会模块之pywin32
    PyMySQL的基本使用
    python:让源码更安全之将py编译成so
    最高分是多少
    哪些技术可以用在WEB开发中实现会话跟踪
    自定义输入模板
    JAVA中HashMap和Hashtable区别
    Java中ArrayList与LinkedList的区别
  • 原文地址:https://www.cnblogs.com/patientAndPersist/p/4381851.html
Copyright © 2011-2022 走看看