本文介绍了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 的内容,但这不起作用

Is there a solution to use String.force_encoding() in Ruby 1.8.7 (or Rails 2.x) so that it works like in Ruby 1.9? I read something about require active_support, but this does not work

$> 宝石列表 --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 中唯一做的就是改变字符串的编码字段,它实际上并没有修改字符串的字节.

The only thing force_encoding does in 1.9 is that it changes the encoding field of the string, it does not actually modify the string's bytes.

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

Ruby 1.8 doesn't have the concept of string encodings, so force_encoding would be a no-op. You can add it yourself like this if you want to be able to run the same code in 1.8 and 1.9:

class String
  def force_encoding(enc)
    self
  end
end

当然,您还需要做其他事情才能使编码在 1.8 和 1.9 中的工作方式相同,因为它们处理这个问题的方式非常不同.

There will of course be other things that you have to do to make encodings work the same across 1.8 and 1.9, since they handle this issue very differently.

这篇关于Ruby 1.8.7(或 Rails 2.x)中的 String.force_encoding()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 04:52