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

Fu8*_*u86 13 ruby gem encoding ruby-on-rails

有没有String.force_encoding()在Ruby 1.8.7(或Rails 2.x)中使用的解决方案,以便它像在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)
Run Code Online (Sandbox Code Playgroud)

$> ruby -v

ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin10.4.0]
Run Code Online (Sandbox Code Playgroud)

$> rails -v

Rails 2.3.8
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Sea*_*ere 21

这将在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
Run Code Online (Sandbox Code Playgroud)

然后...

?> "asdf".to_my_utf8
=> "asdf"
Run Code Online (Sandbox Code Playgroud)

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

  • 那是Paul Battley的贡献......正如他所说的那样,"'危险'字节是那些在194-253范围内的字节"......如果字符串以其中一个结束,转换有时会爆炸. (3认同)

The*_*heo 14

唯一force_encoding确实的1.9是它改变了字符串的编码领域,它实际上并没有修改字符串的字节数.

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

class String
  def force_encoding(enc)
    self
  end
end
Run Code Online (Sandbox Code Playgroud)

当然还有其他一些事情需要做,以使编码在1.8和1.9中的工作方式相同,因为它们处理这个问题的方式截然不同.