本文介绍了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: / p>

 >需要rubygems
=>真
>需要active_support
=>真
> asdf.force_encoding(UTF-8)
NoMethodError:asdf的未定义方法`force_encoding':String
> String.respond_to?(:force_encoding)
=> false


解决方案

唯一的 force_encoding 在1.9中表示,它会更改字符串的编码字段,但实际上并不会修改字符串的字节。



Ruby 1.8不有字符串编码的概念,所以 force_encoding 将是一个无效的。如果你想要在1.8和1.9中运行相同的代码,你可以自己添加它:

  class String $ 



当然还有其他一些事情要做,因为他们处理这个问题是非常不同的,因此编码在1.8和1.9之间是一样的。


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

$> 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
解决方案

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 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

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