简体   繁体   English

在Ruby 1.8.7或1.9.2中进行编码

[英]Encoding in Ruby 1.8.7 or 1.9.2

I have been trying to use the gem 'character-encodings' which doesn't build in 1.9.2 however it does in 1.8.7 but even when I require 'encoding/character/utf-8' I still cant do the simplest of encoding. 我一直在尝试使用不能在1.9.2中构建的gem'character-encodings',但是在1.8.7中可以使用,但是即使我需要'encoding / character / utf-8',我仍然无法做到最简单的编码。

require 'encoding/character/utf-8'
str = u"hëllö"
str.length
  #=> 5
str.reverse.length
  #=> 5
str[/ël/]
  #=> "ël"

I get 我懂了

ruby-1.8.7-p302 >   # encoding: utf-8
ruby-1.8.7-p302 >   require 'encoding/character/utf-8'
 => nil 
ruby-1.8.7-p302 > str = u"hll"
 => u"hll" 
ruby-1.8.7-p302 > str.length
 => 3 
ruby-1.8.7-p302 >   #=> 5
ruby-1.8.7-p302 >   str.reverse.length
 => 3 
ruby-1.8.7-p302 >   #=> 5
ruby-1.8.7-p302 >   str[/l/]
 => "l" 

My question is, is there a really nice encoding library that can accept allot or possibly all the different characters out there. 我的问题是,有没有一个非常好的编码库可以接受分配或所有可能的不同字符。 Or maybe use utf-16? 或者也许使用utf-16? I have tried the magic code "# encoding: utf-8" which didn't seem to do it either. 我尝试了魔术代码“#encoding:utf-8”,该代码似乎也没有。 Thank you 谢谢

I'm afraid I don't understand your question. 恐怕我不明白你的问题。 Are you having issues with the source code file? 您的源代码文件有问题吗? I've tried it both in console and a ruby script (1.8.7), and it does work. 我已经在控制台和ruby脚本(1.8.7)中都尝试过了,并且它确实起作用。

require 'rubygems'
require 'encoding/character/utf-8'
str = u'hëllö'
puts str.length
puts str.reverse.length
puts str[/ël/]

and the output works as expected 并且输出按预期工作

5
5
ël

In Ruby 1.9+ (I tested in 1.9.2 preview) you don't need a library, as encoding is supported by the standard library. 在Ruby 1.9+(我在1.9.2预览版中测试)中,您不需要库,因为标准库支持编码。 See this post for more information about it. 有关更多信息,请参见这篇文章 http://yehudakatz.com/2010/05/05/ruby-1-9-encodings-a-primer-and-the-solution-for-rails/ http://yehudakatz.com/2010/05/05/ruby-1-9-encodings-a-primer-and-the-solution-for-rails/

this works without c extensions and on 1.8/1.9, not all string methods work(but they are easy to add) 这在没有c扩展名的情况下可以工作,并且在1.8 / 1.9上,不是所有的字符串方法都可以工作(但是很容易添加)

https://github.com/grosser/string19 https://github.com/grosser/string19

require 'rubygems'
require 'string19'
String19('hëllö').length == 5

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

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