tags:

views:

128

answers:

1

Does Ruby have an equivalent to .NET's Encoding.ASCII.GetString(byte[])?

Encoding.ASCII.GetString(bytes[]) takes an array of bytes and returns a string after decoding the bytes using the ASCII encoding.

+1  A: 

Assuming your data is in an array like so (each element is a byte, and further, from the description you posted, no larger than 127 in value, that is, a 7-bit ASCII character):

array =[104, 101, 108, 108, 111]

string = array.pack("c*") 

After this, string will contain "hello", which is what I believe you're requesting.

The pack method "Packs the contents of arr into a binary sequence according to the directives in the given template string".

"c*" asks the method to interpret each element of the array as a "char". Use "C*" if you want to interpret them as unsigned chars.

http://ruby-doc.org/core/classes/Array.html#M002222

The example given in the documentation page uses the function to convert a string with Unicode characters. In Ruby I believe this is best done using Iconv:

require "iconv"
require "pp"

#Ruby representation of unicode characters is different
unicodeString = "This unicode string contains two characters " +
                "with codes outside the ASCII code range, " +
                "Pi (\342\x03\xa0) and Sigma (\342\x03\xa3).";

#printing original string
puts unicodeString 

i = Iconv.new("ASCII//IGNORE","UTF-8")

#Printing converted string, unicode characters stripped
puts i.iconv(unicodeString)
bytes = i.iconv(unicodeString).unpack("c*")
#printing array of bytes of converted string
pp bytes

Read up on Ruby's Iconv here.

You might also want to check this question.

Roadmaster
Can you reproduce the example "Pi (\u03a0) and Sigma (\u03a3)." from the C# to Ruby?
Richard Huang
The key part of the example is taking a unicode string and using Encoding.ascii to render it in the ASCII charset. The encodedBytes function does some magic to "strip" unicode characters from the string. From your question I assume what you're after is the actual string as rendered from encodedBytes using GetString. In this case, in Ruby, you're probably better off using Iconv, to which you'd pass the original string containing Unicode characters, Iconv will convert this to an ASCII string (possibly stripping Unicode characters with no ASCII representation). You can then work with this string.
Roadmaster