我对 Nokogiri 文档中发生的事情感到困惑。
据我所知,如果
require 'nokogiri'
some_html = "<html><body><h1>Mr. Belvedere Fan Club</h1></body></html>"
然后这三行做同样的事情:
html_doc = Nokogiri::HTML::Document.parse(some_html)
html_doc = Nokogiri::HTML.parse(some_html)
html_doc = Nokogiri::HTML(some_html)
第二个只是第一个的便捷方法。但在我的非 Ruby 眼中,第三个看起来像是将参数传递给模块,而不是方法。我知道 Ruby 有构造函数,但我认为它们采用的是 Class.new 形式,而不是 Module(args)。这里发生了什么?
最佳答案
只是语法糖,看Nokogiri::HTML模块定义:
module Nokogiri
class << self
###
# Parse HTML. Convenience method for Nokogiri::HTML::Document.parse
def HTML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
Nokogiri::HTML::Document.parse(thing, url, encoding, options, &block)
end
end
module HTML
class << self
###
# Parse HTML. Convenience method for Nokogiri::HTML::Document.parse
def parse thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
Document.parse(thing, url, encoding, options, &block)
end
####
# Parse a fragment from +string+ in to a NodeSet.
def fragment string, encoding = nil
HTML::DocumentFragment.parse string, encoding
end
end
# Instance of Nokogiri::HTML::EntityLookup
NamedCharacters = EntityLookup.new
end
end
首先,他们在名为 HTML 的 Nokogiri 模块中定义了一个类方法(是的,Ruby 允许您这样做),然后他们定义了模块 Nokogiri::HTML 并在其中定义类方法 parse。
大多数人不知道,:: 运算符也可以用来执行方法调用:
"my_string"::size #will print 9
关于Ruby 模块给定参数调用一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6880780/