给定参数的Ruby模块调用方法?
我对Nokogiri文档中发生的事情感到困惑 据我所知,如果给定参数的Ruby模块调用方法?,ruby,Ruby,我对Nokogiri文档中发生的事情感到困惑 据我所知,如果 require 'nokogiri' some_html = "<html><body><h1>Mr. Belvedere Fan Club</h1></body></html>" 第二种方法只是第一种方法的一种方便方法。但在我非Ruby的眼中,第三个看起来像是将参数传递给模块,而不是方法。我知道Ruby有构造函数,但我认为它们的形式是Class.new,而不是
require 'nokogiri'
some_html = "<html><body><h1>Mr. Belvedere Fan Club</h1></body></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
有趣的问题btwformethodcalls,不是,但在尝试访问常量时必须使用::,如Nokogiri::HTML::Document。抱歉,在注释中删除了我的问题。我问他们之间是否有区别。及::。谢谢毛里西奥!
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
"my_string"::size #will print 9