Recently I stumbled over this code snippet in Ruby:
@data = 3.chr * 5
which results in “\003\003\003\003\003”
later in the code for example
flag = @data[2] & 2
is used,
I know that it has something todo with bitwise-flags. It seems the values 1,2 and 3 are used as state flags, but because ruby 1.9, which is the version I am familar with, changed the Integer.chr method the code does no longer work and I would really like to know whats going on.
Furthermore, what is the purpose of the “\00x” escaped-thing?
Thanks for your answers
To make the code work in Ruby 1.9, try changing that line to:
Prior to Ruby 1.9,
str[n]would return an integer between 0 and 255, but in Ruby 1.9 with its new unicode support,str[n]returns a character (string of length 1). To get the integer instead of character, you can call.ordon the character.The
&operator is just the standard bitwise AND operator common to C, Ruby, and many other languages.Byte number three (0x03) is not a printable ASCII character, so when you have that byte in a string and call
inspectruby denotes that byte as\003. Just make sure you understand that “\003” is a single-byte string while ‘\003’ is a four-byte string.In Ruby, strings are really sequences of bytes. In Ruby 1.9, there is also encoding information, but they are still really just a sequence of bytes.