class Nokogiri::HTML4::Document

def meta_encoding=(encoding)

into a head element.
Beware in CRuby, that libxml2 automatically inserts a meta tag

from the document encoding is undefined.
The result when trying to set an encoding that is different

content element (typically ) if any.
is inside a head element if any, and before any text node or
place supplying head and/or html elements as necessary, which
Otherwise, this method tries to create one at an appropriate

replaced with the given text.
If an meta encoding tag is already present, its content is

Set the meta tag encoding for this document.
##
def meta_encoding=(encoding)
  if (meta = meta_content_type)
    meta["content"] = format("text/html; charset=%s", encoding)
    encoding
  elsif (meta = at_xpath("//meta[@charset]"))
    meta["charset"] = encoding
  else
    meta = XML::Node.new("meta", self)
    if (dtd = internal_subset) && dtd.html5_dtd?
      meta["charset"] = encoding
    else
      meta["http-equiv"] = "Content-Type"
      meta["content"] = format("text/html; charset=%s", encoding)
    end
    if (head = at_xpath("//head"))
      head.prepend_child(meta)
    else
      set_metadata_element(meta)
    end
    encoding
  end
end