load works on local path, require doesn't

拈花ヽ惹草 提交于 2019-12-03 04:40:50
Dylan Markow

If you provide just a filename to require, it will only look in the predefined $LOAD_PATH directories. However, if you provide a path with your filename, it should work:

puts 'This is the first (master) program file.'
require './loadee.rb'
puts 'And back again to the first file.'

You could also add your project's folder to the load path instead:

$LOAD_PATH.unshift File.dirname(__FILE__)
puts 'This is the first (master) program file.'
require 'loadee.rb'
puts 'And back again to the first file.'

And last, you could just use require_relative instead:

puts 'This is the first (master) program file.'
require_relative 'loadee.rb'
puts 'And back again to the first file.'

Providing a path with the filename seemed not to work for me, and I didn't want to cram a bunch of paths into my $LOAD_PATH.

Checking out the documentation, I found require_relative.

require_relative 'loadee'

Works in both 1.9.2 and 2.1.2.

The documentation indicates that require is not intended to search relative paths at all, and neither is load.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!