Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

2.37 Encoding and Decoding Base64 Strings

Base64 is frequently used to convert machine-readable data into a text form with no special characters in it. For example, images and fonts stored inline inside CSS files are encoded with Base64.

The easiest way to do a Base64 encode/decode is to use the built-in Base64 module. The Base64 class has an encode64 method that returns a Base64 string (with a newline appended). It also has the method decode64, which changes the string back to its original bytes, as shown here:

require "base64"
str = "\xAB\xBA\x02abdce"
encoded  = Base64.encode64(str)     # "q7oCYWJkY2U=\n"
original = Base64.decode64(encoded) # "\xAB\xBA\x02abdce"
  • + Share This
  • 🔖 Save To Your Account