2016-09-28 4 views
3

私はこのようになりますディレクトリ構造を持っている:私はしようとすると、Rubyは ` 'が必要です。そのようなファイル(とLoadError)をロードすることはできません

require "yp-crawler/file-c" 
require "yp-crawler/file-b" 
require "yp-crawler/file-a" 

module YPCrawler 
end 

- lib 
    - yp-crawler (directory) 
     - file-a.rb 
     - file-b.rb 
     - file-c.rb 
    - yp-crawler.rb 

をマイlib/yp-crawler.rbファイルは次のようになりますこれを行うことにより、コマンドラインで自分のファイルを実行します。

ruby lib/yp-crawler.rb 

私はこのエラーを取得する:

`require': cannot load such file -- yp-crawler/file-c (LoadError) 
    from .rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' 
    from lib/yp-crawler.rb:1:in `<main>' 

これは何が原因でしょうか?

+1

あなたは 'require_relative" file-a "'を試しましたか? – davidhu2000

+1

@ davidhu2000 Bruv ...完璧です。それはうまくいった。それを答えとして加えて、私はそれを受け入れます。ありがとう! – marcamillion

答えて

2

API Dockによれば、require_relativeが必要です。

Ruby tries to load the library named string relative to the requiring file’s path. If the file’s path cannot be determined a LoadError is raised. If a file is loaded true is returned and false otherwise.

だから、あなたがしなければならないすべては、あなたが行うことができます

require_relative "file-a" 
require_relative "file-b" 
require_relative "file-c" 
+0

これは1.8/1.9以降の新しい変化ですか? – marcamillion

3

もう一つは、(これは宝石のほとんどがファイルを必要とする方法である)$LOAD_PATHにディレクトリを追加することです。
$LOAD_PATH(別名$:)は、requireを呼び出したときにルビーがファイルを探す場所です。

だから、

# lib/yp-crawler.rb 

$LOAD_PATH.unshift File.expand_path('..', __FILE__) 
# it can be $LOAD_PATH.push also 

require "yp-crawler/file-c" 
require "yp-crawler/file-b" 
require "yp-crawler/file-a" 

module YPCrawler 
end 

P.S.このコードを試すことができます たとえば、seeと同じことをpaperclipで行うことができます。

+1

私はこれを投稿するつもりでした。 – engineersmnky

関連する問題