2011-05-13 4 views
19

loadee.rb로드는 로컬 경로에서 작동하고 require는

puts '> This is the second file.' 

loaddemo.rb

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

내가 "ruby loaddemo.rb"를 실행하면, 이것은 잘 작동합니다. 두 파일은 같은 디렉토리에 있으며 그 디렉토리는 내가 실행 한 디렉토리입니다.

하지만 확장 또는없이 필요에 부하를 변경하고, 만약 내가 얻을 :

<internal:lib/rubygems/custom_require>:29:in `require': no such file to load 
-- loadee.rb (LoadError) 
     from <internal:lib/rubygems/custom_require>:29:in `require' 
     from loaddemo.rb:2:in `<main>' 

내 질문은 물론이고, 왜이 경우 작업이 필요하지 않습니까? 그래야지, 그렇지? 로드를 수행하고 다른 경로를 사용해야합니까?

루비 버전 1.9.2

답변

38

당신이 require 단지 파일 이름을 제공하는 경우

루비 버전, 그것은 단지 미리 정의 된 $LOAD_PATH 디렉토리에서 찾게됩니다. 당신이 당신의 파일 이름과 경로를 제공하는 경우, 그것을 작동합니다 :

$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.' 

그리고 마지막으로, 당신은 단지 require_relative을 사용할 수

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

또한 대신 부하 경로에 프로젝트의 폴더를 추가 할 수 있습니다 대신 : 파일 이름이 나를 위해 작동하지 않는 것 같았다와

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

로드가없는 이유는 무엇입니까? 그것은 다른 경로 변수를 사용합니까? –

+1

이것은 실제로 루비에 대한 버그로 현재 나열되어 있습니다. 1.9는'require'를 사용할 때로드 경로에서 "현재 디렉토리"를 제거했지만'load'는 제거하지 않았습니다. http://redmine.ruby-lang.org/issues/2710 –

+2

또한,'load'를 사용할 때마다 전체 파일을 평가하는 반면,'require'를 사용하면 처음으로 파일을 평가할 때만 평가한다는 점에 유의하십시오 그것. –

4

는 경로를 제공하고, 내 $LOAD_PATH에 경로의 무리 벼락 공부를하고 싶지 않았다.

documentation을 확인하면 require_relative입니다. 1.9.22.1.2 모두

require_relative 'loadee' 

작품.

documentationload이 아닌 상대 경로를 검색하지 않기 위해 require을 나타냅니다.

관련 문제