What is the difference between require_relative and require in Ruby?

后端 未结 7 1880
深忆病人
深忆病人 2020-11-22 10:15

What is the difference between require_relative and require in Ruby?

7条回答
  •  不知归路
    2020-11-22 10:59

    Summary

    Use require for installed gems

    Use require_relative for local files

    require uses your $LOAD_PATH to find the files.
    require_relative uses the current location of the file using the statement


    require

    Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.

    When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.

    require_relative

    This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use

    require_relative '../../../filename'
    

    (up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).

    Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.

提交回复
热议问题