递归地将包含非UTF字符的散列转换为UTF [英] recursively convert hash containing non-UTF chars to UTF
本文介绍了递归地将包含非UTF字符的散列转换为UTF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个流氓宝石(omniauth),它提供了一个包含ASCII-BIT8字符串的数据的散列表,我想将它转换为UTF。
I have a rogue gem (omniauth) which provides a hash of data containing ASCII-BIT8 strings that I would like to convert into UTF.
如何强制将所有的哈希字符串元素转换为UTF,作为某种类型的rails初始化方法? .to_utf8
How can I force all of the string elements of the hash into UTF, as some kind of rails initializer method? .to_utf8
session[:omniauth] = omniauth.to_utf8
class Hash
def to_utf8
#not really sure what to do here?
end
end
推荐答案
Ruby 1.9通常只需使用 encode
方法翻转编码。与 symbolize_keys
不同的是,这是一个包装器,它可以递归地转换哈希值,这使得它很简单:
In Ruby 1.9 you can usually just flip the encoding using the encode
method. A wrapper around this that recursively transforms the hash, not unlike symbolize_keys
makes this straightforward:
class Hash
def to_utf8
Hash[
self.collect do |k, v|
if (v.respond_to?(:to_utf8))
[ k, v.to_utf8 ]
elsif (v.respond_to?(:encoding))
[ k, v.dup.encode('UTF-8') ]
else
[ k, v ]
end
end
]
end
end
这篇关于递归地将包含非UTF字符的散列转换为UTF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文