Question

Ruby: create a String from bytes

I would like to build a string from a byte value.

I currently use:

str = " "
str[0] = byte

This seems to work fine but I find it ugly and not very scalable to strings longer than 1 character.

Any idea?

 45  46506  45
1 Jan 1970

Solution

 70

There is a much simpler approach than any of the above: Array#pack:

>> [65,66,67,68,69].pack('c*')
=>  "ABCDE"

I believe pack is implemented in c in matz ruby, so it also will be considerably faster with very large arrays.

Also, pack can correctly handle UTF-8 using the 'U*' template.

2009-06-07

Solution

 21

for 1.9 you need:

[195,164].pack('c*').force_encoding('UTF-8')
2011-01-15