- 論壇徽章:
- 0
|
Ruby的require
require一般用來加載其它的類,如:
#Ruby代碼 :- require 'dbi'
- require "rexml/document"
- 復(fù)制代碼
復(fù)制代碼 但是上面加載的是標(biāo)準(zhǔn)類庫里面的文件,當(dāng)然也可以是已安裝的gems文件,
但是如果是自己在本地寫的文件,就不能直接用require了,
而應(yīng)該這樣:- #E7.4-1.rb Module(模塊)
- module Module1
- def sqrt(num, rx=1, e=1e-10)
- num*=1.0
- (num - rx*rx).abs <e ? rx : sqrt(num, (num/rx + rx)/2, e)
- end
- end
- 復(fù)制代碼
復(fù)制代碼- #E7.4-2.rb Person 類
- class Person
- def talk
- puts "I'm talking."
- end
- end
- 復(fù)制代碼
復(fù)制代碼 #用require_relative加載本地Ruby文件- require_relative "E7.4-1"
- require_relative "E7.4-2"
- class Student < Person
- include Module1
- end
- aStudent=Student.new
- aStudent.talk # I'm talking.
- puts aStudent.sqrt(77,2) # 8.77496438739435
- 復(fù)制代碼
復(fù)制代碼 #但是這個(gè)如果想直接通過require的方式來引用也是有辦法的,那就是在文件頭部將當(dāng)前目錄作為ruby加載的路徑:
#其中File.dirname(__FILE__)代表當(dāng)前路徑,而$LOAD_PATH.unshift方法的目的就是將當(dāng)前目錄作用ruby標(biāo)準(zhǔn)的加載路徑- $LOAD_PATH.unshift(File.dirname(__FILE__)) unless $LOAD_PATH.include?(File.dirname(__FILE__))
- require "E7.4-1"
- require "E7.4-2"
- class Student < Person
- include Module1
- end
- aStudent=Student.new
- aStudent.talk # I'm talking.
- puts aStudent.sqrt(77,2) # 8.77496438739435
- 復(fù)制代碼
復(fù)制代碼 |
|