有时候明明是 UTF-8 编码,可是 s.encode('gbk'),转码失败,怎么解决呢? s='5233496214,鐖遍鏅敾,绂忓缓 鑾嗙敯,缁樼敾鐖卞ソ鑰呫€傚井淇″彿锛?35421815,,,f,2085,1999,66,0,2014-07-26 17:51:14,-1,,1894' (utf-8 编码)
试试 str.encode('utf-8','gbk',{:invalid => :replace, :undef => :replace, :replace => '?'})
#8 楼 @bluexuemei 具体说明见:http://www.ruby-doc.org/core-1.9.3/String.html :invalid If the value is :replace, encode replaces invalid byte sequences in str with the replacement character. The default is to raise the Encoding::InvalidByteSequenceError exception
:undef If the value is :replace, encode replaces characters which are undefined in the destination encoding with the replacement character. The default is to raise the Encoding::UndefinedConversionError.
:replace Sets the replacement string to the given value. The default replacement string is “uFFFD” for Unicode encoding forms, and “?” otherwise.
:fallback Sets the replacement string by the given object for undefined character. The object should be a Hash, a Proc, a Method, or an object which has [] method. Its key is an undefined character encoded in the source encoding of current transcoder. Its value can be any encoding until it can be converted into the destination encoding of the transcoder.