Ruby - Logic and Including Code


require and load both act like normal code in Ruby programs.

You can put them at any point in your Ruby code and they'll behave as if they were processed at that point.

For example:

$debug_mode = 0 
require $debug_mode == 0 ? "normal-classes" : "debug-classes" 

Here, the code checks if the global variable $debug_mode is set to 0.

If it is, it requires normal-classes.rb, and if not, debug-classes.rb.

You can include a different source file dependent on the value of a variable.

A commonly used shortcut uses arrays to quickly load a collection of libraries at once. For example:

%w{file1 file2 file3 file4 file5}.each { |l| require l } 

This loads five different external files or libraries with just two lines of code.

Related Topic