0

Just as the title describes, how can I do the following?

require 'base64'

text = 'éééé'
encode = Base64.encode64(text)
Base64.decode64(encode)

Result: éééé instead of \xC3\xA9\xC3\xA9
tadman
  • 200,744
  • 21
  • 223
  • 248
Dan Rubio
  • 4,365
  • 7
  • 39
  • 89

1 Answers1

1

When you decode64 you get back a string with BINARY (a.k.a. ASCII-8BIT) encoding:

Base64.decode64(encode).encoding
# => #<Encoding:ASCII-8BIT>

The trick is to force-apply a particular encoding:

Base64.decode64(encode).force_encoding('UTF-8')
# => "éééé"

This assumes that your string is valid UTF-8, which it might not be, so use with caution.

tadman
  • 200,744
  • 21
  • 223
  • 248