Converting a Byte Array to a String in Ruby
In Converting a Byte Array to String with Buffer
in Node.JS I mentioned about Node.JS Buffer
s, and how they're a way to serialise an array of bytes into a JSON format.
As Ruby is my preferred scripting language, I wanted to document how to convert this back to a String with Ruby, too.
Let us assume that we have the following data:
[
104, 116, 116, 112, 115,
58, 47, 47, 119, 119,
119, 46, 106, 118, 116,
46, 109, 101
]
We can follow grosser's solution (bearing in mind David J's comment):
bytes = [
104, 116, 116, 112, 115,
58, 47, 47, 119, 119,
119, 46, 106, 118, 116,
46, 109, 101
]
puts bytes.pack('C*').force_encoding('UTF-8')
# 'https://www.jvt.me'