Skip to content

Instantly share code, notes, and snippets.

@DavidEGrayson
Last active August 29, 2015 13:58
Show Gist options
  • Save DavidEGrayson/10093790 to your computer and use it in GitHub Desktop.
Save DavidEGrayson/10093790 to your computer and use it in GitHub Desktop.
Ruby snippet that lets you see the actual bytes in a string.

If you deal with a lot of binary data in Ruby, you'll want this snippet of code to add a String#hex_inspect method, because String#inspect makes it hard to see the actual bytes. Example usage:

binary_string = "\x0d\x0e\x00\x40"
binary_string.hex_inspect # => "\x0d\x0e\x00\x40" (good)
binary_string.inspect     # => "\r\x0E\x00@"  (bad)
class String
def hex_inspect
'"' + each_byte.map { |b| '\x%02x' % b }.join + '"'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment