簡體   English   中英

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

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

有沒有在Ruby 1.8.7(或Rails 2.x)中使用String.force_encoding()的解決方案,使其像在Ruby 1.9中一樣工作? 我讀到一些有關require active_support ,但這不起作用

$> 寶石列表--local | grep'rails \\ | activesupport'

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

$> 紅寶石-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

這將在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做過的一些工作。

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上也能正常工作,還需要做其他事情,因為它們處理此問題的方式非常不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM