Search code examples
rubyquotes

Changing Double Quotes to Single


I'm working on a project in Ruby. The library I'm using returns a string in double quotes, for example: "\x00\x40". Since the string is in double quotes, any hex that can be converted to an ASCII character is converted. Therefore, when I print, I actually see: "\x00@".

I figured out that, if I use single quotes, then the string will print in pure hex (without conversion), which is what I want. How do I change a double quoted string to single quoted?

I do not have any way to change the return type in the library since it is a C extension, and I can't figure out where the value is being returned from. Any ideas greatly appreciated.


Solution

  • "\x00\x40" and '\x00\x40' produce totally different strings.

    "\x00\x40" creates a 2 byte string with hex values 0x00 and 0x40:

    "\x00\x40".length
    # => 2
    
    "\x00\x40".chars.to_a
    # => ["\u0000", "@"]
    

    '\x00\x40' creates a string with 8 characters:

    '\x00\x40'.length
    # => 8
    
    '\x00\x40'.chars.to_a
    # => ["\\", "x", "0", "0", "\\", "x", "4", "0"]
    

    This is done by Ruby's parser and you cannot change it once the string is created.

    However, you can convert the string to get its hexadecimal representation.

    String#unpack decodes the string as a hex string, i.e. it returns the hex value of each byte as a string:

    hex = "\x00\x40".unpack("H*")[0]
    # => "0040"
    

    String#gsub adds/inserts \x every 2 bytes:

    hex.gsub(/../) { |s| '\x' + s }
    # => "\\x00\\x40"