简体   繁体   English

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

[英]String.force_encoding() in Ruby 1.8.7 (or Rails 2.x)

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? 有没有在Ruby 1.8.7(或Rails 2.x)中使用String.force_encoding()的解决方案,使其像在Ruby 1.9中一样工作? I read something about require active_support , but this does not work 我读到一些有关require active_support ,但这不起作用

$> gem list --local | $> 宝石列表--local | grep 'rails\\|activesupport' grep'rails \\ | activesupport'

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

$> ruby -v $> 红宝石-v

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

$> rails -v $> rails -v

Rails 2.3.8

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

This will give you String#to_my_utf8 in both Ruby 1.8.7 and Ruby 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

And then... 然后...

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

Inspired by Paul Battley and also remembering some of my older work on the remote_table gem . 受到Paul Battley的启发,还记得我在remote_table gem做过的一些工作。

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. force_encoding在1.9中所做的唯一事情是它更改了字符串的编码字段,而实际上并没有修改字符串的字节。

Ruby 1.8 doesn't have the concept of string encodings, so force_encoding would be a no-op. Ruby 1.8没有字符串编码的概念,因此force_encoding是没有操作的。 You can add it yourself like this if you want to be able to run the same code in 1.8 and 1.9: 如果您希望能够在1.8和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. 当然,要使编码在1.8和1.9上也能正常工作,还需要做其他事情,因为它们处理此问题的方式非常不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM