zoukankan      html  css  js  c++  java
  • [转]ruby中require和load的区别

    转自:http://blog.csdn.net/feigeswjtu/article/details/51176626

    众所周知,ruby里引入其他文件的方式有两种,require和load,但是它们有一定的区别,这里详细说明一下。

    require

    require 方法允许我们载入一个库并且会阻止你加载多次。当我们使用 require 重复加载同一个library时,require方法 将会返回 false。当我们要载入的库在不同的文件时才能使用 require 方法,举个例子:
     
    [ruby] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. <pre name="code" class="ruby">#contant_dome.rb  
    2. ContantDome = 3  
    3. puts "ContantDome = #{ContantDome}"  

    
    我们require多次看看效果:
    [ruby] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. irb(main):001:0> require('/home/webuser/Public/contant_dome.rb')  
    2. ContantDome = 3  
    3. => true  
    4. irb(main):002:0> ContantDome  
    5. => 3  
    6. irb(main):003:0> require('/home/webuser/Public/contant_dome.rb')  
    7. => false  

    load

    load 方法基本和 require 方法功能一致,但它不会跟踪要导入的库是否已被加载。因此当重复使用 load 方法时,也会载入多次。大部分情况我们都会使用 require 来代替 load。但当我们需要每次都要加载时候我们才会使用 load, 例如模块的状态会频繁地变化, 我们使用 load 进行加载,获取最新的状态。我们也举个例子看看:
    [ruby] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. irb(main):001:0>  load('/home/webuser/Public/contant_dome.rb')  
    2. ContantDome = 3  
    3. => true  
    4. irb(main):002:0>  load('/home/webuser/Public/contant_dome.rb')  
    5. /home/webuser/Public/contant_dome.rb:1: warning: already initialized constant ContantDome  
    6. /home/webuser/Public/contant_dome.rb:1: warning: previous definition of ContantDome was here  
    7. ContantDome = 3  
    8. => true  
    我们修改文件里面的内容:
     
    [ruby] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #contant_dome.rb  
    2. ContantDome = 4  
    3. puts "ContantDome = #{ContantDome}"  

    [ruby] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. irb(main):003:0>  load('/home/webuser/Public/contant_dome.rb')  
    2. /home/webuser/Public/contant_dome.rb:1: warning: already initialized constant ContantDome  
    3. /home/webuser/Public/contant_dome.rb:1: warning: previous definition of ContantDome was here  
    4. ContantDome = 4  
    5. => true  
    6. irb(main):004:0> ContantDome  
    7. => 4  
  • 相关阅读:
    PAT顶级 1015 Letter-moving Game (35分)
    PAT顶级 1008 Airline Routes (35分)(有向图的强连通分量)
    PAT顶级 1025 Keep at Most 100 Characters (35分)
    PAT顶级 1027 Larry and Inversions (35分)(树状数组)
    PAT 顶级 1026 String of Colorful Beads (35分)(尺取法)
    PAT顶级 1009 Triple Inversions (35分)(树状数组)
    Codeforces 1283F DIY Garland
    Codeforces Round #438 A. Bark to Unlock
    Codeforces Round #437 E. Buy Low Sell High
    Codeforces Round #437 C. Ordering Pizza
  • 原文地址:https://www.cnblogs.com/linganxiong/p/6109789.html
Copyright © 2011-2022 走看看