Chris Brown
Chris Brown

Reputation: 233

How do you use a class from a different file?

I'm trying to use a class from a different file.

something.rb

class Something
  def initialize
  end
  def getText
    'Some example text'
  end
end

another.rb

class Another
end

somethingVar = Something.new
puts somethingVar.getText

This gives me the error

/usr/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /home/chris/RubymineProjects/untitled1/another.rb
/home/chris/RubymineProjects/untitled1/another.rb:4:in `<top (required)>': uninitialized constant Something (NameError)
    from -e:1:in `load'
    from -e:1:in `<main>'

What am I doing wrong?

Upvotes: 3

Views: 178

Answers (3)

typo
typo

Reputation: 1071

NOTE: It is extremely common to see the file name required WITHOUT the .rb extension, as shown in the examples below.

As others have stated, you must require 'something' if in the same load path.

require 'something'

or require_relative './something', by including the path to the file.

require_relative 'something'

"Aside from looking nicer, this bareword way of referring to the extension is necessary because not all extensions use files ending in .rb. Specifically, extensions written in C are stored in files ending with .so or .dll. To keep the process transparent-that is, to save you the trouble of knowing whether the extension you want uses a .rb file or not-Ruby accepts a bareword and then does some automatic file-searching and trying out of possible filenames until it finds the file corresponding to the extension you have requested."

For more info - http://rubylearning.com/satishtalim/including_other_files_in_ruby.html

Upvotes: 0

Jon Carter
Jon Carter

Reputation: 3406

The most common way to use code like this is via require:

require 'something.rb'

..will enable the use of classes defined within that file, but only if the file can be found either in the Ruby loadpath, or associated with an installed gem.

If you want to write your own, especially for testing or short-term hacking, you'll probably want to use require_relative, which takes a relative path to the file you want to use:

require_relative './something.rb'`

That should work if something.rb is in the same directory as another.rb

More info on various ways to reuse code in Ruby can be found here.

Upvotes: 4

B Seven
B Seven

Reputation: 45943

You have to require the something.rb.

require 'something.rb'

Upvotes: 5

Related Questions