30

在 Ruby 中导入文件时,我遇到了一个真正的菜鸟问题。我正在 Windows XP 中制作一个 Ruby 应用程序。该应用程序的所有类文件都在"C:/Documents/Prgm/Surveyor_Ruby/lib". 但是当我require将一个文件放在另一个文件中时,ruby 和 irb 都找不到所需的文件。

当前目录的内容:

C:\Documents\Prgm\Surveyor_Ruby\lib>dir
 Volume in drive C has no label.
 Volume Serial Number is AAAA-BBBB

 Directory of C:\Documents\Prgm\Surveyor_Ruby\lib

10/09/2010  06:32 PM    <DIR>          .
10/09/2010  06:32 PM    <DIR>          ..
10/08/2010  03:22 PM             5,462 main (commented).rb
10/08/2010  03:41 PM                92 question.rb
10/08/2010  09:06 PM             2,809 survey.rb
10/09/2010  06:25 PM               661 surveyor.rb
10/08/2010  01:39 PM             1,546 test.rb
               5 File(s)         10,570 bytes
               2 Dir(s)  40,255,045,632 bytes free

确认 irb 在正确的目录中:

C:\Documents\Prgm\Surveyor_Ruby\lib>irb
irb(main):001:0> Dir.pwd
=> "C:/Documents/Prgm/Surveyor_Ruby/lib"

...但 irb 无法加载survey.rb:

irb(main):002:0> require 'survey'
LoadError: no such file to load -- survey
        from <internal:lib/rubygems/custom_require>:29:in `require'
        from <internal:lib/rubygems/custom_require>:29:in `require'
        from (irb):2
        from C:/Ruby192/bin/irb:12:in `<main>'
4

7 回答 7

65

这些都不适合我,但这确实:

irb -I .
>require 'file'
 => true
于 2011-11-23T01:03:21.083 回答
11
require './hede'

或者

require_relative 'hede'

这适用于我在 Linux 上的 Ruby (1.9.3) 和 JRuby (1.7.x) 中。我还没有在windows上测试过。

于 2013-03-18T09:09:45.013 回答
9

这个命令怎么样?写起来有点麻烦,但很干净,它应该总是有效的:

➜ $ irb
> 需要“#{Dir.pwd}/file_to_load.rb”
=> 真
于 2012-10-06T11:38:33.207 回答
8

注意到相同的行为,但我的 linux 根让我尝试:.\file.rb它加载到 irb 中。尝试显式声明当前目录。

于 2010-10-10T12:43:30.453 回答
3

这太脏了,但你总是可以在第一行做:

$: << '.'

然后你就去 pwd'ed 要求。这对于使用 IRB 进行交互式/创造性测试非常有用

于 2011-05-29T10:15:30.687 回答
2

我相信之前的两个帖子都是正确的,只是用于不同的用途。在 IRB 中使用带有 的绝对路径require,对于文件,您也可以使用require绝对路径,或者使用require_relative.

于 2010-10-10T02:14:00.590 回答
1

If you're trying to do this with rvmsudo, I found this worked for me:

rvmsudo irb -I '/Absolute/path/to/your/project'
于 2012-09-12T20:30:12.320 回答