Base64 in Ruby
Base64 is a commonly used encoding method in Ruby that converts binary data into printable ASCII characters. Ruby's built-in Base64 module makes it easy to encode and decode data using base64. With just a few lines of code, developers can quickly and easily convert data to and from base64 format. In this guide, we'll explore how to use Ruby's Base64 module to encode and decode data.
Encoding
In this example, we first require the base64 library. Then, we define the string that we want to encode as string_to_encode. We then call the Base64.encode64 method on this string and store the result in the encoded_string variable. Finally, we print out the encoded string using the puts method.
1
2
3
4
5
6
require 'base64'
string_to_encode = "Hello, world!"
encoded_string = Base64.encode64(string_to_encode) #SGVsbG8sIHdvcmxkIQ==
puts encoded_string
Decoding
In Ruby, decoding a base64 encoded string is as simple as calling the decode64 method on the Base64 module. In this example, the decode64 method decodes the encoded_string variable and stores the result in the decoded_string variable.
1
2
3
4
5
6
require 'base64'
encoded_string = "SGVsbG8gV29ybGQh"
decoded_string = Base64.decode64(encoded_string) #"Hello, world!"
puts decoded_string
Ruby Base64 Using Blocks & Iterators
In addition to the standard methods for encoding and decoding base64 in Ruby, there are also several methods that allow for more advanced usage with blocks and iterators.
One such method is Base64.encode64 with a block, which allows you to encode a string in chunks and yield the encoded chunks to a block. This can be useful when encoding large strings or streams of data, as it reduces the amount of memory used during the encoding process. Here's an example of using Base64.encode64 with a block:
1
2
3
4
5
6
7
8
9
10
require 'base64'
input_string = "Hello, world!"
encoded_string = ""
Base64.encode64(input_string) do |chunk|
encoded_string << chunk
end
puts encoded_string #SGVsbG8sIHdvcmxkIQ==