It depends on the version of Ruby you are using (1.8.x or 1.9.x). load
and require
work both on the loadpath of Ruby. You can have a look at it by evaluating $:
inside IRB. In Ruby 1.9.x the current directory is not part of the loadpath, so you have to use the absolute path to your file. Depending on the operating system you are using (Windows 7), this may look like:
c:\Users\mliebelt\Desktop>irb
irb(main):001:0> $:
=> ["C:/apps/ruby/ruby192/lib/ruby/site_ruby/1.9.1", "C:/apps/ruby/ruby192/lib/ruby/site_ruby/1.9.1/i386-msvcrt", "C:/apps/ruby/ruby192/lib/ruby/site_ruby", "C:/apps/ruby/ruby192/lib/ruby/vendor_ruby/1.9.1", "C:/apps/ruby/ruby192/lib/ruby/vendor_ruby/1.9.1/i386-msvcrt", "C:/apps/ruby/ruby192/lib/ruby/vendor_ruby", "C:/apps/ruby/ruby192/lib/ruby/1.9.1", "C:/apps/ruby/ruby192/lib/ruby/1.9.1/i386-mingw32"]
irb(main):002:0> require 'c:/Users/mliebelt/Desktop/ruby'
File c:/Users/mliebelt/Desktop/ruby.rb loaded.
=> true
irb(main):003:0> load 'c:/Users/mliebelt/Desktop/ruby.rb'
File c:/Users/mliebelt/Desktop/ruby.rb loaded.
=> true
By the way, the contents of the file ruby.rb
is:
puts "File #{__FILE__} loaded."
The same session with IRB on Ruby 1.8.x may look like that:
c:\Users\mliebelt\Desktop>irb
irb(main):001:0> $:
=> ["C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/site_ruby/1.8", "C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/site_ruby/1.8/i386-msvcrt", "C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/site_ruby", "C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/vendor_ruby/1.8", "C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/vendor_ruby/1.8/i386-msvcrt", "C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/vendor_ruby", "C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/1.8", "C:/Users/mliebelt/.pik/rubies/Ruby-187-p334/lib/ruby/1.8/i386-mingw32", "."]
irb(main):002:0> require 'ruby'
File ./ruby.rb loaded.
=> true
irb(main):003:0> load 'ruby.rb'
File ./ruby.rb loaded.
=> true
The differences between require
and load
are:
require
does not need the suffix (.rb) of the file
require 'ruby'
and require 'ruby.rb'
are the same
require
reads the file into memory once, so require
should normally be used instead of load
, which reads the file into memory every time functions in the file are called.
So to load files (by using require
or load
), do the following:
- expand your load path by your current directory (if necessary). See Adding a directory to loadpath
- (when using Ruby 1.8.x) Start your program (or IRB) in the directory from which you want to load or require files.