The following is an example of how to use require IN Ruby: rubyrequire.
Files in the same directory, such as/usr/local/ruby/foo. rb and/usr/local/ruby/bar. rb.
If it is directly in foo. rb
require 'bar'
Bar. rb is not found during execution.
This is because
/home/oldsong$ ruby /usr/local/ruby/foo.rb
Find bar. rb in the lib directory installed in ruby and the/home/oldsong/directory. Instead of searching under the directory/usr/local/ruby/of the rb file.
Therefore, in addition to referencing the system rb, relative paths cannot be used in require.
The following describes several methods to reference all rb in a single directory and directory based on my personal experience.
1. Reference an object
Example: Reference file_to_require.rb in the same directory of the current rb.
First, we will introduce three methods.
require File.join(__FILE_, '../file_to_require')。require File.expand_path('../file_to_require', __FILE__)require File.dirname(__FILE__) + '/file_to_require'
File. expand_path is a common practice in Rails.
_ FILE _ is a constant, indicating the absolute path of the current FILE, such as/home/oldsong/test. rb.
Method 4:
$LOAD_PATH.unshift(File.dirname(__FILE__))require 'bar'
Add the directory to the LOAD_PATH variable, and then directly reference the file name.
2. Reference all files in a directory
Ruby does not have the import Java. io .*;
Wildcards cannot be used for reference. It is estimated that wildcards may be added in later versions.
For example, reference all *. rb files under the lib/file in the same directory of the current rb.
Method 1:
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }
Method 2:
A gem.
Https://rubygems.org/gems/require_all