Alexander Mills
Alexander Mills

Reputation: 99960

Making two Ruby classes talk to each other in the same directory

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?

Upvotes: 0

Views: 574

Answers (3)

Sachin Singh
Sachin Singh

Reputation: 7225

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

Upvotes: 2

Matheus Moreira
Matheus Moreira

Reputation: 17020

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.

Upvotes: 2

timpone
timpone

Reputation: 19929

try:

require './otherclass'

and

require './samplecode'

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

Upvotes: 2

Related Questions