require 无法加载此类文件 [英] require cannot load such file

查看:72
本文介绍了require 无法加载此类文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一个目录中有以下 2 个文件:

I have the following 2 files in the same dir:

churn.rb:

 subsystem_names = ['audit', 'fulfillment', 'persistence',    
                     'ui', 'util', 'inventory']
  start_date = month_before(Time.now)       

  puts header(start_date)                   
  subsystem_names.each do | name |
    puts subsystem_line(name, change_count_for(name))   
  end

churn_test.rb:

require "test/unit"
require "churn"    

class ChurnTests < Test::Unit::TestCase 

  def test_month_before_is_28_days
    assert_equal(Time.local(2005, 1, 1),
                 month_before(Time.local(2005, 1, 29)))
  end

end

当我运行 churn_test.rb 时,出现以下错误:

When I run churn_test.rb I get the following error:

/Users/ca/.rbenv/versions/2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- churn (LoadError)
    from /Users/ca/.rbenv/versions/2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from churn-tests.rb:8:in `<main>'

推荐答案

当你需要 sth 时,Ruby 会在 $LOAD_PATH ($:).出于安全考虑,当前工作目录不包含在 $LOAD_PATH 中.您可以将目录显式添加到 $LOAD_PATH

When you require sth, Ruby searches the source in $LOAD_PATH ($:). For security concern, the current working directory is not included in $LOAD_PATH. You can either explicitly add the directory into $LOAD_PATH

$: << File.dirname(__FILE__)

require 'churn'

或使用内核#require_relative 需要一个基于相同目录的模块:

or use the Kernel#require_relative to require a module based on the same directory:

require_relative "churn"

这篇关于require 无法加载此类文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆