title: Ruby Invalid Byte Sequence in UTF-8
body: <p>I have the following code, which gives me an invalid byte sequence error pointing to the scan method in <code>initialize</code>. Any ideas on how to fix this? For what it's worth, the error does not occur when the <code>(.*)</code> between the h1 tag and the closing <code>&gt;</code> is not there.</p>
  
  <pre><code>#!/usr/bin/env ruby
  
  class NewsParser
  
    def initialize
        Dir.glob("./**/index.htm") do |file|
          @file = IO.read file 
          parsed = @file.scan(/&lt;h1(.*)&gt;(.*?)&lt;\/h1&gt;(.*)&lt;!-- InstanceEndEditable --&gt;/im)
          self.write(parsed)
        end
    end
  
    def write output
      @contents = output
      open('output.txt', 'a') do |f| 
        f &lt;&lt; @contents[0][0]+"\n\n"+@contents[0][1]+"\n\n\n\n" 
      end
    end
  
  end
  
  p = NewsParser.new
  </code></pre>
  
  <p>Edit: Here is the error message:</p>
  
  <p><code>news_parser.rb:10:in 'scan': invalid byte sequence in UTF-8 (ArgumentError)</code></p>
  
  <p>SOLVED: The combination of using:
  <code>@file = IO.read(file).force_encoding("ISO-8859-1").encode("utf-8", replace: nil)</code>
  and
  <code>encoding: UTF-8</code>
  solve the issue. </p>
  
  <p>Thanks!</p>