简体   繁体   中英

Ruby - LoadError on require

I have the following two files: main.rb and sort.rb located in the same folder. In main.rb I have the following code:

require 'sort'

Sort.insertion_sort([1,2,3,4]).each {|x| print "#{x}, "}

When I try and run this via ruby main.rb I get the following error:

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

Any ideas why? Thanks

The better way to use

require_relative "sort"

intead of

require "sort"

Thanks, @Jörg W Mittag.

Or you can add a path where ruby should search your files (can be a security risk):

$:.unshift File.join(File.dirname(__FILE__), ".") # current directory
require 'sort'

尝试require 'sort.rb'并检查权限

你还会:

require directory/sort.rb

In Ruby 1.9.2, $: doesn't include the current directory ( '.' ). Either do relative_require instead, or do $: << '.' .

Joerg Mittag says that $: << '.' shouldn't be done because it's a security risk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM