What is the difference between require_relative and require in Ruby?

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

What is the difference between require_relative and require in Ruby?

7条回答
  •  孤街浪徒
    2020-11-22 10:54

    The top answers are correct, but deeply technical. For those newer to Ruby:

    • require_relative will most likely be used to bring in code from another file that you wrote.

    for example, what if you have data in ~/my-project/data.rb and you want to include that in ~/my-project/solution.rb? in solution.rb you would add require_relative 'data'.

    it is important to note these files do not need to be in the same directory. require_relative '../../folder1/folder2/data' is also valid.

    • require will most likely be used to bring in code from a library someone else wrote.

    for example, what if you want to use one of the helper functions provided in the active_support library? you'll need to install the gem with gem install activesupport and then in the file require 'active_support'.

    require 'active_support/all'
    "FooBar".underscore
    

    Said differently--

    • require_relative requires a file specifically pointed to relative to the file that calls it.

    • require requires a file included in the $LOAD_PATH.

提交回复
热议问题