Ruby:如何将潜在的unicode字符串分解为字节 [英] Ruby: How to break a potentially unicode string into bytes

查看:88
本文介绍了Ruby:如何将潜在的unicode字符串分解为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个游戏,该游戏需要用户输入并将其呈现在屏幕上.我为此使用的引擎完全是unicode友好的,因此,如果可能的话,我希望保留该引擎.问题在于渲染循环看起来像这样:

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:

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

我对i18n并不了解很多,但是我知道足以知道上述代码仅对我和说我语言的人有用.我更喜欢这样的东西:

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:

"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.

为了获得更多乐趣,我无法知道该字符串是否实际上是unicode字符串.

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

我正在使用的库确实可以渲染整个字符串,但是我让用户编辑动态内容-如果它们碰到退格键",从本质上讲,我需要知道要切碎多少个字节.结束.

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.

推荐答案

不幸的是,ruby 1.8.x对Unicode的支持很差.在1.9中已解决.但与此同时,与此类似的库( http://snippets.dzone.com/posts/show/4527 )是一个很好的解决方案.使用链接库,您的代码将如下所示:

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:

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

这篇关于Ruby:如何将潜在的unicode字符串分解为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆