`
hideto
  • 浏览: 2650775 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

读Ruby for Rails的思考之require与load

    博客分类:
  • Ruby
阅读更多
首先看看代码:
reqdemo.rb
puts "This is the first (master) program file."
require "requiree.rb'
require "requiree.rb'
puts "And back again to the first file."

loaddemo.rb
puts "This is the first (master) program file."
load "requiree.rb'
load "requiree.rb'
puts "And back again to the first file."

requiree.rb
puts "> This is the second file, which was 'require'd by the first."

分别运行reqdemo.rb和loaddemo.rb,结果是require只打印一次,而load打印两次
这是因为:
require load and include
Ruby中"require","load"和"include"有什么不同呢?"require"和"load"用途是一致的,用來来载入新的程序库,"include"是用来mix-in模块

"require"可载入某个a.rb文件,且可以省略".rb",而且它只会在第一次的时候载入,若再次"require"时就会忽略
require 'a'
a = A.new


"load"和"require"一样但要用 a.rb 全名, 且每次一定会重新载入
load 'a.rb'
a = A.new


载入程序库的顺序呢?类似java的class path,Ruby把这个信息存在"$:"系统全局变量上,你可以借着RUBYLIB或ruby -I来加入新的载入目录
puts $:


"include"用来mix-in某个模块,可以减少书写的长度
require 'webrick'
include WEBrick

# 可以不用 server = WEBrick::HTTPServer.new(...)
server = HTTPServer.new(...)


那么load有什么用呢?
Rails程序优先使用load而不是require来载入程序库
在development模式下,当你修改一段代码后,不用重启服务器,你的代码更改会被自动reload,这就是load的作用
而如果你使用require的话,多次require并不会起作用
对大型Ruby程序如Rails,使用多个文件和require/load/include令你的程序非常容易组织和划分模块
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics