Ruby中的UTF-8错误

Noa*_*ark 4 ruby encoding utf-8

我正在抓几个网站,最终我遇到了一个UTF-8错误,看起来像这样:

/usr/local/lib/ruby/gems/1.9.1/gems/dm-core-1.2.0/lib/dm-core/support/ext/blank.rb:19:in
`=~': invalid byte sequence in UTF-8 (ArgumentError)
Run Code Online (Sandbox Code Playgroud)

现在,我不关心网站是否100%准确.有没有办法我可以采取我得到的页面并删除任何问题编码,然后在我的程序内传递它?

我正在使用,ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin11.2.0]如果这很重要.

更新:

def self.blank?(value)
      return value.blank? if value.respond_to?(:blank?)
      case value
      when ::NilClass, ::FalseClass
        true
      when ::TrueClass, ::Numeric
        false
      when ::Array, ::Hash
        value.empty?
      when ::String
        value !~ /\S/ ###This is the line 19 that has the issue.
      else
        value.nil? || (value.respond_to?(:empty?) && value.empty?)
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

当我尝试保存以下行时:

What Happens in The Garage Tin Sign2. � � Newsletter Our monthly newsletter,
Run Code Online (Sandbox Code Playgroud)

它抛出错误.它在页面上:http://www.stationbay.com/.但奇怪的是,当我在我的网络浏览器中查看它时,它并没有在源代码中显示有趣的符号.

接下来我该怎么办?

Nik*_* B. 6

问题是你的字符串包含非UTF-8字符,但似乎强制使用UTF-8编码.以下简短代码演示了此问题:

a = "\xff"
a.force_encoding "utf-8"
a.valid_encoding?  # returns false
a =~ /x/           # provokes ArgumentError: invalid byte sequence in UTF-8
Run Code Online (Sandbox Code Playgroud)

解决此问题的最佳方法是从头开始应用正确的编码.如果这不是一个选项,您可以使用String#encode:

a = "\xff"
a.force_encoding "utf-8"
a.valid_encoding?  # returns false

a.encode!("utf-8", "utf-8", :invalid => :replace)
a.valid_encoding?  # returns true now
a ~= /x/           # works now
Run Code Online (Sandbox Code Playgroud)

  • 在ruby 1.9,2.0:a.encode!("utf-8","utf-8",:invalid =>:replace)a.valid_encoding?#SLEL返回错误 (4认同)