我在正确使用模块方面遇到一些问题。
我有:
module Utilities
def file_search()
# some code
return x
end
end
module Remake_Components
require 'csv'
include Utilities
f = Utilities.file_search()
end
这给了我错误:
#<NoMethodError: undefined method "file_search" for Utilities:Module>
我本以为 f
是运行 file_search
函数的结果。
我的理解是我必须使用
include
关键字才能使用其他方法中的函数,但似乎并非如此?
file_search
是Utilities
中定义的实例方法,而不是“类实例方法”或“模块函数”。
如果您希望它以这种方式工作,那么您有 2 个选择:
Utilities
的特征类上定义方法,将方法更改为 def self.file_search
module_function
方法,例如module Utilities
def file_search()
# some code
return x
end
module_function :file_search
end
这两个选项都允许您拨打
Utilities.file_search
;但是,后者还允许您在使用 Module#include
时“包含”此方法作为私有实例方法。
举例来说:
module A
def self.foo
'Foo'
end
def bar
'Bar'
end
module_function :bar
end
class B
include A
def test_foo
A.foo
end
def test_bar
bar
end
end
A.foo
#=> "Foo"
A.bar
#=> "Bar"
B.new.test_foo
#=> "Foo"
B.new.test_bar
#=> "Bar"
B.new.foo
#=> undefined method `foo' for #<B:0x00007f0c7785e528> (NoMethodError)
B.new.bar
#=> private method `bar' called for #<B:0x00007ff5a5dbe5a0> (NoMethodError)