Search code examples
rubystringbinaryunpack

Undo string to binary in ruby


I have a code to transform from string to binary:

> s = "Anatomía Según Grey"
=> "Anatomía Según Grey"

> s.unpack("a*").first
=> "Anatom\xC3\x83\xC2\xADa Seg\xC3\x83\xC2\xBAn Grey"

How can I get the original string (undo the unpack)?


Solution

  • The conversion is equivalent to:

    s = "Anatomía Según Grey"
    #=> "Anatomía Según Grey"
    
    s.force_encoding('BINARY')
    #=> "Anatom\xC3\x83\xC2\xADa Seg\xC3\x83\xC2\xBAn Grey"
    

    It can be "reversed" via: (you might have to adjust the 'UTF-8' part)

    s.force_encoding('UTF-8')
    #=> "Anatomía Según Grey"
    

    force_encoding doesn't change the string, it just defines how the bytes are interpreted.

    To fix the string, you probably have to call encode in addition:

    "Anatomía Según Grey".encode('ISO-8859-1').force_encoding('UTF-8')
    #=> "Anatomía Según Grey"