Ruby require 'file' doesn't work but require './file' does. Why?

前端 未结 3 1212
广开言路
广开言路 2021-02-14 02:25

I have a folder full of ruby files, and when I try and require one file in another that is in the same directory using require \'file\' I get a LoadError

相关标签:
3条回答
  • 2021-02-14 03:04

    If you want to require a file not from the system $LOAD_PATH but rather relative to the directory of the file you are requireing from, you should use require_relative. (Which, as you can see, isn't exactly extensively documented.)

    0 讨论(0)
  • 2021-02-14 03:09

    Though it is very old post I think some extra information will be very useful to beginner.

    The best way to think of require is in relation to the UNIX $PATH variable. Just by way of a refresher, the $PATH variable in UNIX is a list of directories where executables can be found. So when you type the name of a program on any UNIX terminal, your computer is looking through the executable files in the directories specified in your $PATH variable. require does something very similar. When, for example, you write require 'set' at the top of your Ruby file, you are telling Ruby to look through a bunch of directories for a library called set.rb (Ruby's set library).

    So where does Ruby look for set.rb? Well, once again, Ruby has something very similar to UNIX's $PATH variable. It is the global variable $LOAD_PATH also sometimes known by it's ugly and undescriptive alias $: (which I don't suggest using by the way--short though it may be). It is an array of directory names where Ruby looks when it comes across a require.

    There is nice informative post here where you can get more information about require, load and require_relative

    0 讨论(0)
  • 2021-02-14 03:22

    You don't have current directory in your loadpath.

    Check the contents of the $LOAD_PATH variable

    0 讨论(0)
提交回复
热议问题