zoukankan      html  css  js  c++  java
  • ruby中require load include extend auload方法的区别 小青年

    原文:http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/

    Require:

    require方法让你加载一个库,并且只加载一次,如果你多次加载会返回false。只有当你要加载的库位于一个分离的文件中时才有必要使用require。使用时不需要加扩展名,一般放在文件的最前面:

        require ‘test_library’

    Load:

    load用来多次加载一个库,你必须指定扩展名:

       load ‘test_library.rb’

    Include:

    当 你的库加载之后,你可以在你的类定义中包含一个module,让module的实例方法和变量成为类本身的实例方法和类变量,它们mix进来了。根据锄头 书,include并不会把module的实例方法拷贝到类中,只是做了引用,包含module的不同类都指向了同一个对象。如果你改变了module的 定义,即使你的程序还在运行,所有包含module的类都会改变行为。

       module Log
           def class_type
               “This class is of type: #{self.class}”
           end
       end
       class TestClass
           include Log
       end
       tc=TestClass.new.class_type    #=>This class is of type: TestClass

    Extend:

    extend会把module的实例方法作为类方法加入类中:

       module Log
           def class_type
               “This class is of type: #{self.class}”
           end
       end
       class TestClass
           extend Log
       end
       tc=TestClass.class_type       #=>This class is of type: TestClass

    使用autoload,只有使用到需要的常量或类文件才被加载。。我们真正需要用某个文件时才加载,而require是直接加载,不管你是否会用到。

  • 相关阅读:
    第六章:单元测试框架unittest
    Jenkins 使用 war包安装时,如果出现报离线错误解决方法
    Appium自动化封装教案
    yaml文件读取(5.1之前与5.1之后对比)
    appium-desktop配置运用方法
    postwoman 配置
    jwt解析
    pytest
    centos安装python3.8
    linux 查找命令
  • 原文地址:https://www.cnblogs.com/perish/p/3086414.html
Copyright © 2011-2022 走看看