Ruby:如何将潜在的unicode字符串分解为字节

时间:2021-07-21 21:44:36

I'm writing a game which is taking user input and rendering it on-screen. The engine I'm using for this is entirely unicode-friendly, so I'd like to keep that if at all possible. The problem is that the rendering loop looks like this:

我正在编写一个用户输入并在屏幕上呈现它的游戏。我正在使用的引擎完全是unicode友好的,所以我想尽可能地保留它。问题是渲染循环如下所示:

"string".each_byte do |c|
    render_this_letter(c)
end

I don't know a whole lot about i18n, but I know enough to know the above code is only ever going to work for me and people who speak my language. I'd prefer something like:

我对i18n了解不多,但我知道上面的代码只会对我和说我的语言的人有用。我更喜欢这样的东西:

"unicode string".each_unicode_letter do |u|
    render_unicode_letter(u)
end

Does this exist in the core distribution? I'm somewhat averse to adding additional requirements to the install, but if it's the only way to do it, I'll live.

这是否存在于核心分发中?我有点厌恶为安装添加额外的要求,但如果这是唯一的方法,我会活着。

For extra fun, I have no way of knowing if the string is, in fact, a unicode string.

为了额外的乐趣,我无法知道字符串实际上是否是一个unicode字符串。

EDIT: The library I'm using can indeed render entire strings, however I'm letting the user edit what comes up on the fly - if they hit 'backspace', essentially, I need to know how many bytes to chop off the end.

编辑:我正在使用的库确实可以呈现整个字符串,但是我让用户编辑动态出现的内容 - 如果它们点击'退格',基本上,我需要知道要删除多少字节。

2 个解决方案

#1


2  

Unfortunately ruby 1.8.x has poor unicode support. It's being addressed in 1.9. But in the mean time, libraries like this one (http://snippets.dzone.com/posts/show/4527) are a good solution. Using the linked library, your code would look something like this:

不幸的是,ruby 1.8.x的unicode支持很差。它在1.9中得到解决。但与此同时,像这样的图书馆(http://snippets.dzone.com/posts/show/4527)是一个很好的解决方案。使用链接库,您的代码看起来像这样:

"unicode_string".each_utf8_char do |u| 
    render_unicode_letter(u)
end

#2


2  

You could try including the ActiveSupport::CoreExtensions::String::Unicode module from the rails codebase.

您可以尝试从rails代码库中包含ActiveSupport :: CoreExtensions :: String :: Unicode模块。

#1


2  

Unfortunately ruby 1.8.x has poor unicode support. It's being addressed in 1.9. But in the mean time, libraries like this one (http://snippets.dzone.com/posts/show/4527) are a good solution. Using the linked library, your code would look something like this:

不幸的是,ruby 1.8.x的unicode支持很差。它在1.9中得到解决。但与此同时,像这样的图书馆(http://snippets.dzone.com/posts/show/4527)是一个很好的解决方案。使用链接库,您的代码看起来像这样:

"unicode_string".each_utf8_char do |u| 
    render_unicode_letter(u)
end

#2


2  

You could try including the ActiveSupport::CoreExtensions::String::Unicode module from the rails codebase.

您可以尝试从rails代码库中包含ActiveSupport :: CoreExtensions :: String :: Unicode模块。