2

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
  • 208,517
  • 23
  • 234
  • 262
Dan Rubio
  • 4,709
  • 10
  • 49
  • 106

2 Answers2

5

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
  • 208,517
  • 23
  • 234
  • 262
0

Just use Base64's encode and decode method:

require 'base64'
=> true
Base64.encode64('aksdfjd')
=> "YWtzZGZqZA==\n"

Base64.decode64 "YWtzZGZqZA==\n"
=> "aksdfjd"
Siwei
  • 19,858
  • 7
  • 75
  • 95