The following is an example of how to use require IN Ruby: rubyrequire.

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.