2007年6月28日 星期四

Ruby 中 “require”, “load” 和 “include” 有甚麼不同呢?

請參考這裡 http://anw.stikipad.com/ocean/show/require+load+and+include
require” 和 “load” 用途是一致的, 用來載入新的程式庫, “include” 是用來 mix-in 模組.

1. “require” 可載入某個 a.rb 檔案, 且可以省略 ”.rb”. 而且它只會在第一次的時候載入, 若再次 “require” 時就會忽略
require 'a'
a = A.new


2. “load” 和 “require” 一樣但要用 a.rb 全名, 且每次一定會重新載入
load 'a.rb'
a = A.new

3. 載入程式庫的順序呢(類似 java class path)? Ruby 把這個資訊存在 ”$:” 系統全域變數上, 你可以藉著 RUBYLIB 或 ruby -I 來加入新的載入目錄.
puts $:

4. “include” 用來 mix-in 某個模組, 可以減少書寫的長度
require 'webrick'
include WEBrick

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

沒有留言: