我必须使用Ruby文件:一个包含一些模块,其中包含一些统计计算方法,另一个文件我想调用模块中的一个方法。 我怎么能在Ruby中做到这一点?
这是正确的方法吗?
require 'name of the file with the module'
a=[1,2,3,4]
a.method1
答案 0 :(得分:4)
需要文件的绝对路径,除非该文件位于Ruby的一个加载路径中。您可以使用puts $:
查看默认加载路径。通常会执行以下操作之一来加载文件:
将主文件的目录添加到加载路径,然后使用带有require:
的相对路径$: << 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#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 :(得分:2)
如果您的模块文件位于require搜索路径中,那么您的方法是正确的。
如果您的模块提供了对象本身使用的方法,则必须执行以下操作:
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)