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, newsgroups that handle binary files such as program executables frequently will use base64.

The easiest way to do a base64 encode/decode is to use the built-in features of Ruby. The Array class has a pack method that returns a base64 string (given the parameter “m”). The String class has a method unpack that likewise unpacks the string (decoding the base64):

str = "\007\007\002\abdce"

new_string = [str].pack("m")         # "BwcCB2JkY2U="
original   =  new_string.unpack("m") # ["\a\a\002\abdce"]

Note that an array is returned by unpack.

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.