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
的内容,但这不起作用
$> 宝石列表 --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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将为您提供 Ruby 1.8.7 和 Ruby 1.9 中的 String#to_my_utf8:
然后...
受到 Paul Battley 还记得我在 remote_table gem。
This will give you String#to_my_utf8 in both Ruby 1.8.7 and Ruby 1.9:
And then...
Inspired by Paul Battley and also remembering some of my older work on the remote_table gem.
force_encoding
在 1.9 中唯一做的事情是它改变了字符串的编码字段,它实际上并没有修改字符串的字节。Ruby 1.8 没有字符串编码的概念,因此
force_encoding
将是一个空操作。如果您希望能够在 1.8 和 1.9 中运行相同的代码,您可以自己添加它:当然,您还需要做其他事情才能使编码在 1.8 和 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 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: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.