ruby中require和load的区别

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

require

require 方法允许我们载入一个库并且会阻止你加载多次。当我们使用 require 重复加载同一个library时,require方法 将会返回 f alse。当我们要载入的库在不同的文件时才能使用 require 方法,举个例子:

<pre name="code" class="ruby">#contant_dome.rb
ContantDome = 3
puts "ContantDome = #{ContantDome}"

 我们require多次看看效果: 
irb(main):001:0> require('/home/webuser/Public/contant_dome.rb')
ContantDome = 3
=> true
irb(main):002:0> ContantDome
=> 3
irb(main):003:0> require('/home/webuser/Public/contant_dome.rb')
=> false

load

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

#contant_dome.rb
ContantDome = 4
puts "ContantDome = #{ContantDome}"

irb(main):003:0>  load('/home/webuser/Public/contant_dome.rb')
/home/webuser/Public/contant_dome.rb:1: warning: already initialized constant ContantDome
/home/webuser/Public/contant_dome.rb:1: warning: previous definition of ContantDome was here
ContantDome = 4
=> true
irb(main):004:0> ContantDome
=> 4



  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值