require一般用来加载其它的类,如:
#
Ruby代码 :
require ' dbi '
require " rexml/document "
require ' dbi '
require " rexml/document "
但是上面加载的是标准类库里面的文件,当然也可以是已安装的gems文件,
但是如果是自己在本地写的文件,就不能直接用require了,
而应该这样:
#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
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
#E7.4-2.rb Person 类
class Person
def talk
puts " I'm talking. "
end
end
class Person
def talk
puts " I'm talking. "
end
end
#用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
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
#但是这个如果想直接通过require的方式来引用也是有办法的,那就是在文件头部将当前目录作为ruby加载的路径:
#其中File.dirname(__FILE__)代表当前路径,而$LOAD_PATH.unshift方法的目的就是将当前目录作用ruby标准的加载路径
$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
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