Ruby 1.8.7(或Rails 2.x)中的String.force_encoding()

有没有在Ruby 1.8.7(或Rails 2.x)中使用String.force_encoding()的解决方案,以便它像在Ruby 1.9中一样工作? 我读了一些关于require active_support ,但这不起作用

$> gem list –local | grep’rails \ | activesupport’

  activesupport (3.0.3, 2.3.8, 2.3.5) rails (2.3.8, 2.3.5) 

$> ruby -v

 ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin10.4.0] 

$> rails -v

 Rails 2.3.8 

IRB:

 > require "rubygems" => true > require "active_support" => true > "asdf".force_encoding("UTF-8") NoMethodError: undefined method `force_encoding' for "asdf":String > String.respond_to?(:force_encoding) => false 

force_encoding在1.9中唯一做的就是它改变了字符串的编码字段,它实际上并没有修改字符串的字节。

Ruby 1.8没有字符串编码的概念,因此force_encoding将是一个无操作。 如果您希望能够在1.8和1.9中运行相同的代码,可以像这样自己添加它:

 class String def force_encoding(enc) self end end 

当然,除了1.8和1.9之外,还需要做其他事情来使编码工作相同,因为它们处理这个问题的方式截然不同。

这将在Ruby 1.8.7和Ruby 1.9中为您提供String#to_my_utf8:

 require 'iconv' class String def to_my_utf8 ::Iconv.conv('UTF-8//IGNORE', 'UTF-8', self + ' ')[0..-2] end end 

然后…

 ?> "asdf".to_my_utf8 => "asdf" 

灵感来自Paul Battley ,还记得我在remote_table gem上的一些旧作。