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

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

问题描述

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

Ruby 中的 requireinclude 有什么区别?如果我只想使用类中某个模块的方法,我应该require 还是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?

推荐答案

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

答案:

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 方法将所有的来自另一个模块的方法和将它们包含到当前模块中.这是语言级别的事情,因为与文件级的东西相反要求.包含方法是扩展"类的主要方法其他模块(通常称为混入).例如,如果您的班级定义方法每个",你可以包括混合模块 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.

来源

因此,如果您只想使用一个模块,而不是扩展它或进行混合,那么您将需要使用 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 的 include 完全不同>.

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天全站免登陆