Ruby中include和require有什么区别? [英] What is the difference between include and require in Ruby?

查看:110
本文介绍了Ruby中include和require有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题类似于什么是Ruby中包含和扩展之间的区别?

require 和<$之间有什么区别?在Ruby中c $ c> include ?如果我只想使用我班级模块中的方法,我应该要求它还是包含呢?

What's the difference between require and include in Ruby? If I just want to use the methods from a module in my class, should I require it or include it?

推荐答案



include和require之间的区别是什么? Ruby?

答案:

include和require方法做
非常不同的事情。

The include and require methods do very different things.

在大多数其他编程
语言中,require方法执行包括
的操作:运行另一个文件。它还
跟踪你在
过去所需的内容,并且不需要两次相同的文件
。要运行另一个没有
这个添加功能的文件,你可以使用
加载方法。

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.

include方法接受所有
方法来自另一个模块,
将它们包含在当前模块中。
这是一个语言级别的东西,因为
与文件级别的东西相反,与
要求相反。 include方法是
使用
其他模块(通常称为
mix-ins)扩展类的主要方法。例如,如果您的类
定义方法each,则
可以包含mixin模块Enumerable
,它可以充当集合。这个
可能会令人困惑,因为包含动词
在其他
语言中的使用方式非常不同。

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

所以如果你只是想使用一个模块,而不是扩展它或者混合它-in,然后你要使用 require

So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require.

奇怪的是,Ruby的 require 类似于C的 include ,而Ruby的 include 几乎不像C的包含

Oddly enough, Ruby's require is analogous to C's include, while Ruby's include is almost nothing like C's include.

这篇关于Ruby中include和require有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆