I have to Ruby files: one contains a module with some methods for statistical calculation, in the other file I want to call one of the methods in the module. How can I do that in Ruby?

Is that the right way?

require 'name of the file with the module'

a=[1,2,3,4]
a.method1
up vote 3 down vote accepted

Require needs the absolute path to the file unless the file is located in one of Ruby's load paths. You can view the default load paths with puts $:. It is common to do one of the following to load a file:

Add the main file's directory to the load path and then use relative paths with require:

$: << File.dirname(__FILE__)
require "my_module"

Ruby 1.8 code that only loads a single file will often contain a one-liner like:

require File.expand_path("../my_module", __FILE__)

Ruby 1.9 added require_relative:

require_relative "my_module"

In the module you will need to define the methods as class methods, or use Module#module_function:

module MyModule
  def self.method1 ary
    ...
  end

  def method2
    ...
  end
  module_function :method2
end

a = [1,2,3,4]
MyModule.method1(a)

Your way is correct if your module file is in the require search path.

If your module provide methods to be used by the object itself, you must do:

require 'name of the file with the module'

a=[1,2,3,4]
a.extend MyModule   # here "a" can use the methods of MyModule
a.method1

See Object#extend.

Otherwise, if you'll use the methods directly by the module, you'll use:

MyModule.method1(a)

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.