Bryan
Bryan

Reputation: 3280

How to reference a method in another Ruby code file?

I have a Ruby code file (somelogic.rb) that contains several methods and classes, located in say, /home/user/code. Now I'm writing another class in the same directory and would like to reference to the methods and classes in somelogic.rb. How do I do that? I greatly appreciate any input.

Upvotes: 25

Views: 41716

Answers (4)

mliebelt
mliebelt

Reputation: 15525

Here is the scenario:

/home/user/code/somelogic.rb
class MyMath
  def self.sin(number)
    ...
  end
end

You want to use the methods sin in your other file mylogic.rb.

Depending on the version of ruby, do one the following:

Ruby 1.8.x
require "somelogic"
class OtherThings
  def some_method
    MyMath.sin(42)
  end
end

The use pattern is for all ruby versions the same, but the require statement may be different.

Ruby 1.9.x
require_relative "somelogic"

or variation

Ruby 1.9.x
require "./somelogic"

The first variation works all the time, the second one only if you call ruby mylogic.rb in the directory where mylogic.rb and somelogic.rb are located.

If you want to load files from that directory from a starting point located in another directory, you should use:

Ruby 1.8.x and Ruby 1.9.x
$: << File.dirname(__FILE__)

This expands the load path of Ruby. It reads the (relative) path of __FILE__, gets its directory, and adds the (absolute) path of that directory to your load path. So when doing then the lookup by require, the files will be found.

Upvotes: 18

David Grayson
David Grayson

Reputation: 87406

If you are using Ruby 1.9 or later, this is the simplest way to do it:

require_relative 'somelogic'

If you want your code to work in 1.9 and older versions of Ruby, you should do this instead:

require File.join File.dirname(__FILE__), 'somelogic'

Whichever line you choose, you should put it at the top of your ruby file. Then any classes, modules, or global variables defined in somelogic.rb will be available to your program.

Upvotes: 35

Bhushan Lodha
Bhushan Lodha

Reputation: 6862

In second file (say otherlogic.rb) write require '/home/user/code/somelogic.rb' on first line.

Upvotes: -3

Doug R
Doug R

Reputation: 5779

Check out Ruby's require keyword

Upvotes: 0

Related Questions