Ruby module for arguments invokes method?

I am confused by what is going on in the Nokogiri docs.

As far as i can judge if

require 'nokogiri' some_html = "<html><body><h1>Mr. Belvedere Fan Club</h1></body></html>" 

then these three lines do the same thing:

 html_doc = Nokogiri::HTML::Document.parse(some_html) html_doc = Nokogiri::HTML.parse(some_html) html_doc = Nokogiri::HTML(some_html) 

The second is just a convenience method for the first. But for my eyes other than Ruby, the third one looks like it passes an argument to the module, not the method. I understand that Ruby has constructors, but I thought they took the form of Class.new, not Module (args). What's going on here?

+8
ruby
source share
1 answer

This is just sugar syntax, look at the definition of the Nokogiri :: HTML module:

 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 

First they define a class method in a Nokogiri module called HTML (yes, Ruby allows this), then they define a Nokogiri :: HTML module, and there they define a parse class method.

Most people do not know, but the :: operator can also be used to make method calls:

 "my_string"::size #will print 9 
+8
source share

All Articles