59

I'm a little confused about why my project can't load the files it needs, it's a really simple project tree:

processor/
  bin/
  lib/
    processor.rb
    processor/
      mapper.rb
      reducer.rb

and my processor.rb file looks like

require 'processor/mapper'
require 'processor/reducer'

class Processor

end

And just for testing it that file mapper looks like:

class Mapper
  def run
    puts "running map"
  end
end

But running ruby lib/processor.rb results in:

<internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- processor/mapper (LoadError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from lib/processor.rb:3:in `<class:Processor>'
    from lib/processor.rb:2:in `<main>'    
Andrew Grimm
  • 74,534
  • 52
  • 194
  • 322
JP Silvashy
  • 44,746
  • 48
  • 146
  • 219
  • 1
    "Ruby's" has an apostrophe because you're indicating the load paths belong to it, rather than that there's multiple rubies. – Andrew Grimm Jul 27 '11 at 03:35

3 Answers3

78

Ruby's $LOAD_PATH will not include your lib directory by default (even though that's where the file you're running is located).

You can either tell the ruby interpreter to include it:

ruby -Ilib lib/processor.rb

Or you can add the lib folder to the load path:

$LOAD_PATH.unshift(File.dirname(__FILE__))
require  'processor/mapper'
...
Dave Schweisguth
  • 34,335
  • 10
  • 90
  • 114
Dylan Markow
  • 120,567
  • 26
  • 279
  • 199
35

Ruby 1.9 no longer includes "." in the load path. Do require "#{File.dirname(__FILE__)}/processor/mapper" or use require_relative.

You can always determine the current load path by inspecting $LOAD_PATH (or $:)

(edited: $LOAD_PATH not $:LOAD_PATH)

vcsjones
  • 133,702
  • 30
  • 291
  • 279
cam
  • 13,982
  • 1
  • 41
  • 28
  • 3
    His exact scenario actually wouldn't work in 1.8 either (running `ruby lib/processor.rb` from the root `processor` folder). However, running `ruby processor.rb` while in the `lib` folder would work on 1.8, but not on 1.9. – Dylan Markow Jul 12 '11 at 21:52
6

Use Ruby's require_relative in this case:

require_relative "processor/mapper"
Aldo 'xoen' Giambelluca
  • 11,319
  • 7
  • 31
  • 39