tvdb中的汉尼拔剧集中有一些奇怪的角色.

例如:

Œuf

于是鲁比吐了出来:

./manifesto.rb:19:in `encode': "\xC3" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError)
    from ./manifesto.rb:19:in `to_json'
    from ./manifesto.rb:19:in `<main>'

第19行是:

puts @tree.to_json

有没有办法处理这些非utf字符?我宁愿不替换它们,而是转换它们?还是忽略它们?我不知道,谢谢你的帮助.

奇怪的是,通过cron,脚本可以正常工作.手动运行会产生错误.

推荐答案

It seems you should use another encoding for the object. You should set the proper codepage to the variable @tree, for instance, using instead of by using @tree.force_encoding('ISO-8859-1'). Because ASCII-8BIT is used just for binary files.

要查找ruby的当前外部编码,请发布:

Encoding.default_external

If solves the problem, the problem was in default codepage (encoding), so to resolve it you have to set the proper default codepage (encoding), by either:

  1. In ruby to change encoding to or another proper one, do as follows:

    Encoding.default_external = Encoding::UTF_8
    
  2. In , grep current valid set up:

    $ sudo env|grep UTF-8
    LC_ALL=ru_RU.UTF-8
    LANG=ru_RU.UTF-8
    

    然后以类似的方式将其正确设置为.bashrc,但不能完全使用ru_RU语言,例如:

    export LC_ALL=ru_RU.UTF-8
    export LANG=ru_RU.UTF-8
    

Ruby相关问答推荐

有没有办法把条件语句写得更干净?

带有(*)签名的Ruby方法

如何使用正则表达式在字符串中查找特定匹配项

Ruby注入daisy链?

Ruby 中的字符串是可变的吗?

我如何 expect期望在 RSpec 中引发异常的东西?

Ruby 中的发送方法

Ruby - 查看端口是否打开

为什么整数除法在许多脚本语言中舍入?

在 jekyll 博客中支持标签的简单方法

rails 控制台、RVM 和 readline 的问题

删除/取消定义类方法

相当于 Ruby 中的通过

如何只获取没有命名空间的类名

如何在 Ruby 中读取整个文件?

将哈希传递给函数 ( *args ) 及其含义

为依赖于环境变量的代码编写规范的最佳方法是什么?

如何从字符串创建 Ruby 日期对象?

何时在 Ruby 中使用 Struct 而不是 Hash?

我更改存储库 URL 后 Capistrano 部署失败