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

Example

files

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

PS C:\Users\Administrator\RubyCode> ls


Mode                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.rb

puts "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.rb

puts "> This is the second file."

run

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

PS C:\Users\Administrator\RubyCode> ruby loaddemo.rb

This 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> irb

irb(main):001:0> "Hello world".scanf("%s%s")
NoMethodError: undefined method `scanf' for "Hello world":String
Did you mean?  scan
        from (irb):1
        from C:/Ruby23-x64/bin/irb.cmd:19:in `<main>'

irb(main):002:0> require "scanf"
=> true
irb(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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值