Ruby:从字节创建字符串 [英] Ruby: create a String from bytes
本文介绍了Ruby:从字节创建字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字节值构建一个字符串。
I would like to build a string from a byte value.
我当前使用的是:
str = " "
str[0] = byte
这似乎很好用,但我觉得它很丑陋,而且对长度超过1个字符的字符串不是很可扩展。
This seems to work fine but I find it ugly and not very scalable to strings longer than 1 character.
任何想法吗?
推荐答案
比上述任何一种方法都简单得多:数组#pack :
There is a much simpler approach than any of the above: Array#pack:
>> [65,66,67,68,69].pack('c*')
=> "ABCDE"
我相信打包是在Matz红宝石中用c实现的,因此它的速度也要快得多
I believe pack is implemented in c in matz ruby, so it also will be considerably faster with very large arrays.
此外,pack可以使用'U *'模板正确处理UTF-8。
Also, pack can correctly handle UTF-8 using the 'U*' template.
这篇关于Ruby:从字节创建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文