Is there a shorter way to require a file in the same directory in ruby? Is there a shorter way to require a file in the same directory in ruby? ruby ruby

Is there a shorter way to require a file in the same directory in ruby?


Since ruby 1.9 you can use require_relative.

Check the latest doc for require_relative or another version of the Core API.


Just require filename.

Yes, it will import it twice if you specify it as filename and ./filename, so don't do that. You're not specifying the .rb, so don't specify the path. I usually put the bulk of my application logic into a file in lib, and then have a script in bin that looks something like this:

#!/usr/bin/env ruby$: << File.join(File.dirname(__FILE__), "/../lib")require 'app.rb'App.new.run(ARGV)

Another advantage is that I find it easier to do unit testing if the loading the application logic doesn't automatically start executing it.


The above will work even when you're running the script from some other directory.However, inside the same directory the shorter forms you refer to work as expected and at least for ruby 1.9 won't result in a double-require.

testa.rb

puts "start test A"require 'testb'require './testb'puts "finish test A"

testb.rb

puts "start test B"puts "finish test B"

running 'ruby testa.rb' will result in:

start test Astart test Bfinish test Bfinish test A

However, the longer form will work even from another directory (eg. ruby somedir/script.rb)