ruby same - Best way to require all files from a directory in ruby?

6 Answers

How about:

Dir["/path/to/directory/*.rb"].each {|file| require file }
require_relative path

What's the best way to require all files from a directory in ruby ?

Dir.glob(File.join('path', '**', '*.rb'), &method(:require))

or alternatively, if you want to scope the files to load to specific folders:

Dir.glob(File.join('path', '{folder1,folder2}', '**', '*.rb'), &method(:require))


Dir.glob takes a block as argument.

method(:require) will return the require method.

&method(:require) will convert the method to a bloc.

Instead of concatenating paths like in some answers, I use File.expand_path:

Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
  require file


Instead of using File.dirname you could do the following:

Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
  require file

Where .. strips the filename of __FILE__.

In Rails, you can do:

Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }

Update: Corrected with suggestion of @Jiggneshh Gohel to remove slashes.

And what about: require_relative *Dir['relative path']?


ruby file directory require