基础 Ruby 中 Include, Extend, Load, Require 的使用区别

原文链接: Ruby Require VS Load VS Include VS Extend

Include

如下例当你Include一个模块到某个类时, 相当于把模块中定义的方法插入到类中。它允许使用 mixin。它用来 DRY 你的代码, 避免重复。例如, 当你有多个类时, 需要相同的函数时, 可以把函数定义到module中, 进行include。
下例假设模块Log和类TestClass在相同的.rb文件。如果它们存在于多个文件, 则需要使用 load 或 require 导入文件。

module Log 
  def class_type
    "This class is of type: #{self.class}"
  end
end

class TestClass 
  include Log 
end

tc = TestClass.new.class_type
puts tc #This class is of type: TestClass

Extend

当你使用Extend来替换 Include 的时候, 你会添加模块里的方法为类方法, 而不是实例方法。详细请看例子:

module Log
  def class_type
    "This class is of type: #{self.class}"
  end
end
 
class TestClass
  extend Log
  # ...
end
 
tc = TestClass.class_type
puts tc  # This class is of type: TestClass

当你在类中使用 Extend 来代替 Include, 如果你实例化 TestClass 并调用 class_type方法时,你将会得到 NoMethodError。再一次强调, 使用 Extend 时方法是类方法。

Require

Require 方法允许你载入一个库并且会阻止你加载多次。当你使用 require 重复加载同一个library时,require方法 将会返回 false。当你要载入的库在不同的文件时才能使用 require 方法。下例将演示 require 的使用方式。

文件 test_library.rb 和 test_require.rb 在同一个目录下。

# test_library.rb
puts " load this libary "
# test_require.rb
puts (require './test_library')
puts (require './test_library')
puts (require './test_library')
# 结果为
#  load this libary 
# true
# false
# false

Load

Load 方法基本和 require 方法功能一致,但它不会跟踪要导入的库是否已被加载。因此当重复使用 load 方法时,也会载入多次。大部分情况你都会使用 require 来代替 load。但当你需要每次都要加载时候你才会使用 load, 例如模块的状态会频繁地变化, 你会使用 load 进行加载,获取最新的状态。

puts load "./test_library.rb"  #在这里不能省略 .rb, require可以省略
puts load "./test_library.rb" 
puts load "./test_library.rb" 
#结果
# load this libary
#true
# load this libary
#true
# load this libary
#true
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、心得体会1、今天完成了什么? 今天看了20页的镐头书(139-160) 看了10个controller 2、今...
    柳辉阅读 2,773评论 0 0
  • 声明 本文系 sinatra 源码系列第 2 篇。系列的目的是通过 sinatra 学习 ruby 编程技巧。文章...
    coffeeplease阅读 3,973评论 0 1
  • ruby 的命名规则局部变量:以英文字母或者_开头,如:name = "this is a local varia...
    云莉6阅读 4,204评论 0 0
  • 1 Node.js模块的实现 之前在网上查阅了许多介绍Node.js的文章,可惜对于Node.js的模块机制大都着...
    zlx_2017阅读 5,161评论 0 1
  • 服务器集群 MS DB1 T1 P1 scp 传输文件 MS 跳板服务器,公钥登陆其他三台机器。 关闭其余三台服务...
    Weiliam阅读 1,742评论 0 0