我的问题类似于“Ruby中include和extend的区别是什么?”
Ruby中require和include的区别是什么?如果我只是想在我的类中使用模块中的方法,我应该要求它还是包含它?
我的问题类似于“Ruby中include和extend的区别是什么?”
Ruby中require和include的区别是什么?如果我只是想在我的类中使用模块中的方法,我应该要求它还是包含它?
当前回答
您曾经尝试过要求一个模块吗?结果如何?试试:
MyModule = Module.new
require MyModule # see what happens
模块不是必需的,只是包含的!
其他回答
来自编程Ruby 1.9
We’ll make a couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. Second, a Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.
您曾经尝试过要求一个模块吗?结果如何?试试:
MyModule = Module.new
require MyModule # see what happens
模块不是必需的,只是包含的!
例如:当你使用require 'math'时,你必须写math::PI。 但是当你使用include math时,你可以简单地写成PI。
'Load'-插入文件内容。(每次调用文件时解析文件)
'Require'-插入一个文件解析的内容。(文件解析一次,存储在内存中)
'Include'-将模块包含到类中,并可以使用模块内的方法作为类的实例方法
'Extend'-将模块包含到类中,并可以使用模块内的方法作为类方法
如果你正在使用一个模块,这意味着你要把所有的方法都带入你的类中。 如果你用一个模块扩展一个类,这意味着你把模块的方法作为类方法“引入”了。 如果你在模块中包含了一个类,这意味着你将模块的方法作为实例方法“引入”了。
EX:
module A
def say
puts "this is module A"
end
end
class B
include A
end
class C
extend A
end
B.say =>未定义的方法'说'的B:类
B.new.say 这是模块A
C.say 这是模块A
C.new.say =>未定义的方法'说' C:类