ruby 知识点

$LOAD_PATH 执行 require 读取文件时搜索的目录名数组,也可以写作 $:


创建 URI 的时候可以直接这样

URI("http://www.dy2018.com/i/97519.html")

看上去像是用一个类名直接接收一个参数来创建的,但是其实在 uri 库中的 common.rb 中有这么一段

module Kernel

  #
  # Returns +uri+ converted to a URI object.
  #
  def URI(uri)
    if uri.is_a?(URI::Generic)
      uri
    elsif uri = String.try_convert(uri)
      URI.parse(uri)
    else
      raise ArgumentError,
        "bad argument (expected URI object or URI string)"
    end
  end
  module_function :URI
end

很明显,这里往 Kernel 里加了一个名字特殊(大写,并且跟 URI 类同名)的模块方法。再来看看 kernel.rb 中关于 Kernel 模块的一段注释

# The Kernel module is included by class Object, so its methods are
# available in every Ruby object.
# 
# The Kernel instance methods are documented in class Object while 
# module methods are documented here.  These methods are called without a
# receiver and thus can be called in functional form:
# 
#   sprintf "%.1f", 1.234 #=> "1.2"
module Kernel
    ...
end

综上,最上面用于创建 URI 的关键字 “URI” 其实是 Kernel 的一个模块方法,只是故意定义得和 URI 类同名而已。

转载于:https://www.cnblogs.com/shang1jk/p/6219256.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值