Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: create a String from bytes

Tags:

string

ruby

byte

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?

like image 587
Vincent Robert Avatar asked Jun 06 '09 22:06

Vincent Robert


2 Answers

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.

like image 160
Jason Watkins Avatar answered Nov 17 '22 23:11

Jason Watkins


for 1.9 you need:

[195,164].pack('c*').force_encoding('UTF-8')
like image 21
grosser Avatar answered Nov 18 '22 00:11

grosser