【问题标题】:incompatible character encodings: UTF-8 and ASCII-8BIT Ruby 1.9不兼容的字符编码:UTF-8 和 ASCII-8BIT Ruby 1.9
【发布时间】:2010-09-08 11:34:18
【问题描述】:

我刚刚升级到 ruby​​ 1.92,我的一个猴子补丁因某种编码错误而失败。我有以下功能:

  def strip_noise()
    return if (!self) || (self.size == 0)

    self.delete(160.chr+194.chr).gsub(/[,]/, "").strip
  end

现在给我以下错误:

不兼容的字符编码: UTF-8 和 ASCII-8BIT

还有其他人遇到过这个吗?

【问题讨论】:

标签: ruby


【解决方案1】:

无论如何,这对我有用:

class String
  def strip_noise()
    return if empty? 
    self.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'')
  end
end

我需要做更多的测试,但我可以进步..

【讨论】:

    【解决方案2】:
    class String
      def strip_noise
        return if empty? 
        ActiveSupport::Inflector.transliterate self, ''
      end
    end
    
    "#{160.chr}#{197.chr} string with noises" # => "\xA0\xC5 string with noises"
    "#{160.chr}#{197.chr} string with noises".strip_noise # => "A string with noises"
    

    【讨论】:

      【解决方案3】:

      这可能不是你想要的:

        def strip_noise
          return if empty?
          sub = 160.chr.force_encoding(encoding) + 194.chr.force_encoding(encoding)
          delete(sub).gsub(/[,]/, "").strip
        end
      

      在此处阅读有关该主题的更多信息:http://yehudakatz.com/2010/05/17/encodings-unabridged/

      【讨论】:

      • 我现在得到“UTF-8 中的无效字节序列”。 160.chr 和 194.chr 不是有效的 UTF-8 字符吗?
      • 不知道,显然不是。为什么不将实际字符而不是字节放在那里。还是将字符串本身转换为 ASCII-8BIT?
      【解决方案4】:

      尚不完全清楚您要在这里做什么,但160.chr+194.chr 不是有效的 UTF-8:160 是连续字节,194 是 2 字节字符的第一个字节。反过来,它们形成了“不间断空格”的 unicode 字符。

      如果你想删除所有非 ASCII-7 字符,试试这个:

      s.delete!("^\u{0000}-\u{007F}")
      

      【讨论】:

        猜你喜欢
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 2014-12-11
        • 2011-07-14
        • 2012-07-12
        • 1970-01-01
        • 2011-10-17
        • 2011-03-12
        相关资源
        最近更新 更多