How to convert string to bytes in Ruby?

With the help of unpack we can convert the string into any format:- byte, bite(MSB,LSB), ASCII or hex. please go through this link:- http://blog.bigbinary.com/2011/07/20/ruby-pack-unpack.html. To convert string into bytes:-

"abcde".unpack('c*')  
=> [97, 98, 99, 100, 101]

String#bytes returns enumerator through string bytes.

"asd".bytes
=> [97, 115, 100]

In Ruby 1.9.3 the #bytes was returning an Enumerator so you had to add .to_a to convert it to an Array. Since 2.3 or maybe even earlier you don't have to add it anymore.


Ruby already has a String#each_byte method which is aliased to String#bytes.

Prior to Ruby 1.9 strings were equivalent to byte arrays, i.e. a character was assumed to be a single byte. That's fine for ASCII text and various text encodings like Win-1252 and ISO-8859-1 but fails badly with Unicode, which we see more and more often on the web. Ruby 1.9+ is Unicode aware, and strings are no longer considered to be made up of bytes, but instead consist of characters, which can be multiple bytes long.

So, if you are trying to manipulate text as single bytes, you'll need to ensure your input is ASCII, or at least a single-byte-based character set. If you might have multi-byte characters you should use String#each_char or String.split(//) or String.unpack with the U flag.


What does // mean in String.split(//)

// is the same as using ''. Either tells split to return characters. You can also usually use chars.

Tags:

Ruby