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 类同名而已。

posted @ 2016-12-25 12:03  shang1jk  阅读(183)  评论(0编辑  收藏  举报