gpt4 book ai didi

ruby - Ruby 中的 include 和 require 有什么区别?

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:10 24 4
gpt4 key购买 nike

我的问题类似于“What is the difference between include and extend in Ruby?”。

Ruby 中的 requireinclude 有什么区别?如果我只是想在我的类中使用模块中的方法,我应该require 还是include

最佳答案

What's the difference between "include" and "require" in Ruby?

Answer:

The include and require methods do very different things.

The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.

The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.

Source

因此,如果您只想使用一个模块,而不是扩展它或进行混合,那么您将需要使用 require

奇怪的是,Ruby 的require 类似于C 的include,而Ruby 的include 几乎与C 的include 完全不同>.

关于ruby - Ruby 中的 include 和 require 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/318144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com