Search code examples
rubyrequirefilepath

Require Not Working in Ruby


I have two files person.rb and contact_info.rb and the person.rb file contains a class, and the contact_info.rb file contains a module. When i do load 'person.rb' in irb this works fine when load 'contact_info.rb' is at the top of this file.

When I switch this to require 'contact_info.rb' at the top of the person.rb file, and in irb do require 'person.rb' I get an error (i've included the error at the bottom of this text and it's using a completely different file path.

I've googled some solutions such as using './person.rb' and require_relative 'person' but these don't work either.

I've simplified the code within files to make things easier.

Any help would be awesome.

CODE IN THE person.rb FILE

require 'contact_info.rb'
  class Person
    include ContactInfo
  end

CODE IN THE contact_info.rb FILE

module  ContactInfo
  #some code
end

ERROR MESSAGE THAT I'M GETTING - when I type in require 'person.rb' in irb.

**note - when i drag the file into the command line the file path is /Volumes/New\ Passport/All\ Creative/Ruby/module_folder_tut/person.rb

LoadError: cannot load such file -- person.rb
  from /Users/paulknight/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/paulknight/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from (irb):1
from /Users/paulknight/.rvm/rubies/ruby-2.4.1/bin/irb:11:in `<main>'

Solution

  • Current directory in NOT on the ruby search path by default. Add it to $: and everything will be fine (assuming you are launching irb from the directory where person.rb is located):

    $: << "."
    require "person.rb"
    

    More detailed info.