Hola
Hola

Reputation: 910

Does 'require' in Ruby not include subfolders automatically?

If I have this folder structure:

rexml
rexml/document

Is the following syntax not a recursive reference that includes everything below it?

require 'rexml'

Or do I need to write the following if I also want to access what's in 'document'?:

require 'rexml/document'

The reason I'm confused is I see some code where the author writes both require statements one after the other:

require 'rexml'
require 'rexml/document'

I wasn't sure if this was really necessary.

Upvotes: 3

Views: 2169

Answers (2)

Chuck
Chuck

Reputation: 237060

Ruby's standard require only loads Ruby files, not folders or anything else. When you say "require 'rexml'", you're actually saying "look for 'rexml.rb' in one of the paths in $: and load it." Thus, "require 'rexml/document'" looks for the file "document.rb" in the folder "rexml" in one of the paths in $:.

Upvotes: 11

Greg Campbell
Greg Campbell

Reputation: 15302

In Ruby, require requires only a single file. In many cases, authors of libraries/gems will ensure that that single file requires all other code necessary to use the library, however - see these lines in the nokogiri library, for instance. This can vary from library to library, however, and in the case of REXML it appears that you do need to require 'rexml/document'.

Upvotes: 6

Related Questions