Ruby – How to call a method from a module of an other ruby file

methodsmoduleruby

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

Best Answer

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)