class Nokogiri::HTML::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
  case
  when meta = meta_content_type
    meta['content'] = 'text/html; charset=%s' % encoding
    encoding
  when meta = at('//meta[@charset]')
    meta['charset'] = encoding
  else
    meta = XML::Node.new('meta', self)
    if dtd = internal_subset and dtd.html5_dtd?
      meta['charset'] = encoding
    else
      meta['http-equiv'] = 'Content-Type'
      meta['content'] = 'text/html; charset=%s' % encoding
    end
    case
    when head = at('//head')
      head.prepend_child(meta)
    else
      set_metadata_element(meta)
    end
    encoding
  end
end