0

I have two .rb files in the same directory

samplecode.rb
otherclass.rb

here is the contents of SampleCode

require 'otherclass'
include OtherClass

class SampleCode
  #...
end

and here is the contents of OtherClass

require 'samplecode'

class OtherClass
  #...
end

when I run "ruby otherclass.rb" I get the following error:

enter image description here

I can't figure out what's going wrong, because these two files are definitely in the same directory. What gives?

Zach Kemp
  • 11,736
  • 1
  • 32
  • 46
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    You have a lot going wrong here. You should not be including `samplecode` inside `otherclass` AND `otherclass` in `sampleclass` It should be a one way include. This will lead to circular dependencies. – Justin Wood Mar 20 '14 at 00:02
  • 1
    @JustinWood, to what extent are circular dependencies between Ruby files a problem? Ruby won't load the same file twice. – Matheus Moreira Mar 20 '14 at 00:27

3 Answers3

2

try:

require './otherclass'

and

require './samplecode'

require should handle circular references issue but your current dir is probably not in your path.

timpone
  • 19,235
  • 36
  • 121
  • 211
2

The require method searches for files in Ruby's $LOAD_PATH, which doesn't include your current directory for security reasons. So, when you require 'sample_code', it will look all over your system for that file and fail to find it, because it is in your current directory.

You should add the current directory to the search path so that Ruby will find your script:

ruby -l . other_class.rb

Note that it won't work if you try to run the script from outside the directory where sample_code.rb is in. Worse; if a different file with the same name is in the current directory, it will be loaded and executed instead of your script. This is a possible attack vector, and the reason why the current directory is not in the search path.

Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
2

try this out:

use require_relative when loading the file not present ruby's $LOAD_PATH

read it for more info on require and require_relative

Community
  • 1
  • 1
Sachin Singh
  • 7,107
  • 6
  • 40
  • 80