Join my Laravel for REST API's course on Udemy 👀

Base64 encode a Ruby hash

August 8, 2022  ‐ 1 min read

The best option I've found to base64 encode a hash in Ruby is by first converting the hash to a JSON string. After which we can base64 encode it. This can be easily decoded by another program by first base64 decode the string and next parse the result as JSON.

require 'base64'
require 'json'

hash = {id: 1, slug: 'boo'}
result = Base64.encode64(JSON.dump(hash))
#=> "eyJpZCI6MSwic2x1ZyI6ImJvbyJ9\n"

Make sure to require both the base64 and json modules. The result of the operation can be decoded as follows:

#=> {"id"=>1, "slug"=>"boo"}