2012-04-24 33 views
1

我必須使用Ruby文件:其中一個包含一個用於統計計算的某些模塊的模塊,另一個文件中我想調用模塊中的其中一個方法。 我如何在Ruby中做到這一點?如何從其他紅寶石文件的模塊中調用方法

這是正確的方法嗎?

require 'name of the file with the module' 

a=[1,2,3,4] 
a.method1 

回答

3

要求需要文件的絕對路徑,除非文件位於Ruby的加載路徑之一中。您可以使用puts $:查看默認加載路徑。這是常見的執行下列操作之一來加載一個文件:

添加主文件的目錄負載路徑,然後使用相對路徑與要求:

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

的Ruby 1.8的代碼,只加載單文件通常會包含一個班輪,如:

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

Ruby 1.9的加入require_relative:

require_relative "my_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) 
1

你的方法是正確的,如果你的模塊文件是在需要搜索路徑。

如果你的模塊提供的方法來通過對象本身可以使用,你必須做到:

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 

Object#extend

否則,如果您將通過該模塊直接使用的方法,您將使用:

MyModule.method1(a)