tags:

views:

1240

answers:

3

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?

A: 

If bytes is an array of Fixnum's you could try this:

bytes.map {|num| num.chr}.join

or this:

s = ''
bytes.each {|i| s << i}
hyperlogic
+1  A: 

can't remember if there is a single function that does that:

>> a = [65,66,67]
=> [65, 66, 67]
>> a.map {|x| x.chr}.join
=> "ABC"
動靜能量
Nice, did not know about the chr method
Vincent Robert
+3  A: 

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.

Jason Watkins