Require vs Load

本文通过实验对比了Ruby中Require与Load两个方法的区别:Require能够自动添加文件扩展名并阻止重复加载,而Load则需要显式指定扩展名且允许重复加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址 : http://www.fromjavatoruby.com/2008/10/require-vs-load.html

关于两者的区别,原文讲的很清楚,这里只做简单翻译和实验,记录一下省得忘记

 

Require官方文档Kernel#require ,Load官方文档Kernel#load


区别有2点:

1.Load需要显示指出扩展名(LoadError)而require不用,require会自动加上.rb,.so,.o,.dll完成加载。
2.Load可以重复加载多次而require不行(第二次加载返回false)。

 

实验 :test.rb和 run.rb在同一目录。

test.rb

puts "This file is so useful I just want to use it everywhere!"

 run.rb

def reqFile(file)
  require file
end

def loadFile(file)
  load file
end

puts "\n"
puts 'reqFile Method1 ...'
puts reqFile('test')
puts 'reqFile Method1 ...'

puts "\n"
puts 'reqFile Method2 ...'
puts reqFile('test')
puts 'reqFile Method2 ...'

puts "\n"
puts 'loadFile Method1 ...'
puts loadFile('test.rb')
puts 'loadFile Method1 ...'

puts "\n"
puts 'loadFile Method2 ...'
puts loadFile('test.rb')
puts 'loadFile Method2 ...'

puts "\n"
puts 'loadFile Method3 ...'
puts loadFile('test')
puts 'loadFile Method3 ...'

 输出:

>ruby run.rb
run.rb:6:in `load': no such file to load -- test (LoadError)
	from run.rb:6:in `loadFile'
	from run.rb:31

reqFile Method1 ...
This file is so useful I just want to use it everywhere!
true
reqFile Method1 ...

reqFile Method2 ...
false
reqFile Method2 ...

loadFile Method1 ...
This file is so useful I just want to use it everywhere!
true
loadFile Method1 ...

loadFile Method2 ...
This file is so useful I just want to use it everywhere!
true
loadFile Method2 ...

loadFile Method3 ...
>Exit code: 1
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值