Ruby 中 require 与 include
本文将阐明 Ruby 中 require 和 include 之间的区别。
为了实现可重用性并使维护更容易获得,我们必须将我们的功能划分为文件和模块。
程序员可以在每个文件中定义任意数量的模块。
在 Ruby 中使用 require
方法
文件名作为字符串传递给 require
方法。它可以是文件的路径,例如 ./my dir/file a.rb
或没有扩展名的简单文件名,例如 file a.rb.
当你使用 require,
时,文件中的代码将被评估并执行。
该示例显示了如何使用 require
。in file a.rb
消息将由 file a.rb
中的文件代码打印。
我们将通过在文件 file b.rb
中调用 require 'file_a'
来加载 file_a
。将打印字符串 in file_a.rb
的结果。
# file_a.rb
puts 'in file_a.rb'
# file_b.rb
require 'file_a'
输出:
in file_a.rb
在 Ruby 中使用 include
方法
与加载整个文件代码的 require
不同,include
采用模块名称并使其所有方法可用于其他类或模块。
下面是 Ruby 中 include 语句的语法。当我们从名为 HelloWorld
的类中调用实例方法 greet
时,我们得到一个缺失错误。
class HelloWorld; end
HelloWorld.new.greet
输出:
NoMethodError: undefined method `greet' for #<HelloWorld:0x007faa8405d5a8>
然后我们创建一个 Greeting
模块并将其包含在我们之前创建的类中。之后调用 greet
将打印一条消息。
module Greeting
def greet
puts 'How are you doing?'
end
end
HelloWorld.include(Greeting)
HelloWorld.new.greet
输出:
How are you doing?
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。