[Ruby笔记]6. Ruby load require 使用对比

来源:互联网 发布:2017淘宝双十一攻略 编辑:程序博客网 时间:2024/06/05 07:54

Example

files

当前目录下有两个文件 loaddemo.rb 以及 loadee.rb

PS C:\Users\Administrator\RubyCode> lsMode                LastWriteTime     Length Name----                -------------     ------ -----a---         2016/5/19      1:47        182 loaddemo.rb-a---         2016/5/19      1:31         33 loadee.rb

code

两个文件的源码分别如下 : (# 是Ruby的注释符号

PS C:\Users\Administrator\RubyCode> more loaddemo.rbputs "This is the first(master) program file."# load "loadee.rb"# require "./loadee.rb"# require "./loadee"require_relative "loadee"puts "And back again to the first file."PS C:\Users\Administrator\RubyCode> more loadee.rbputs "> This is the second file."

run

四种用法效果都是一样的,第一句和第三句来自loaddemo.rb 第二句来自laodee.rb

PS C:\Users\Administrator\RubyCode> ruby loaddemo.rbThis is the first(master) program file. > This is the second file.And back again to the first file.

load vs require

difference

  • require 只会加载一次,同名的方法不会被二次加载,一般来说 require a feature(not require a file)
  • load 可以多次加载,文件如果有部分改写,会随即更新;

usage

下面是典型的require a feature用法:

PS C:\Users\Administrator\RubyCode> irbirb(main):001:0> "Hello world".scanf("%s%s")NoMethodError: undefined method `scanf' for "Hello world":StringDid you mean?  scan        from (irb):1        from C:/Ruby23-x64/bin/irb.cmd:19:in `<main>'irb(main):002:0> require "scanf"=> trueirb(main):003:0> "Hello world".scanf("%s%s")=> ["Hello", "world"]

Extra

Ruby extension ( written in the C programming language).

Reference

《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
1.3. Ruby extensions and programming libraries

ロケット噴射~      / |     /  |  ∧ ∧/   | (゚Д゚/   /_/ つ/   /て ) /   //∪    /\ /   /|  \_ / |  /// \| ωωhttp://emoji.vis.ne.jp/rocket4.htm
0 0
原创粉丝点击