How to Decode Base64 in Ruby with unpack1
Base64 turns bytes into plain text so they can travel in JSON, URLs or environment variables. Ruby can decode it with a method every string already has, unpack1('m0'), so no library has to be loaded.
Syntax
<bytes> = <text>.unpack1('m0')
<text> = [<bytes>].pack('m0')
| Part | What it does |
|---|---|
unpack1 | Reads one value out of a string using a format directive. |
'm0' | The base64 directive, strict form: it raises an error for invalid input. |
[<bytes>].pack('m0') | The way back: encodes bytes as base64 text without line breaks. |
The Ruby documentation on packed data describes 'm' as a "Base64 encoded string" and adds that "if count is zero, no newlines are added", which is what the 0 in 'm0' asks for.
The Example
The example decodes SGVsbG8=, the base64 form of the word Hello, and prints it with p and puts.
Prerequisites
- Ruby. This guide uses Ruby 4.0.10.
Step 1: Write the Code
Create a file named main.rb:

data = 'SGVsbG8='.unpack1('m0')
p data
puts data
Step 2: Run It
ruby main.rb
"Hello"
Hello

The decoded value is a string holding the bytes of Hello. The command is the same in zsh, bash and PowerShell.
Why m0 and Not m
'm0' is strict: 'SGV*bG8='.unpack1('m0') raised invalid base64 (ArgumentError). The lenient 'm' doesn't complain; on the same input it returned "He[\e", bytes that look valid but aren't what was encoded. Use 'm0' so broken input fails loudly.
Base64url
Base64url, used in JWTs and URLs, writes - and _, which 'm0' rejects with the same invalid base64 error. The base64 gem, which comes with Ruby as a bundled gem, decodes it: require 'base64' and Base64.urlsafe_decode64('-_8') returned the bytes "\xFB\xFF".
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using 'm' for untrusted input | Invalid characters produce wrong bytes without an error | Use 'm0' |
Decoding base64url with 'm0' | invalid base64 (ArgumentError) | Use Base64.urlsafe_decode64 |
| Treating decoded bytes as text | Random bytes, such as a key, print as garbage | Keep them as a binary string |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
invalid base64 (ArgumentError) | A character outside the alphabet, or base64url input | Clean the input, or use the URL-safe decoder |
| Strange characters after decoding | The data isn't text | Inspect it with p, or check its bytesize |
FAQ
What does unpack1 return compared to unpack?
unpack returns an array of every decoded value; unpack1 returns just the first, which is all you need for one base64 string.
How do I encode?
['Hello'].pack('m0') returned "SGVsbG8=".
Conclusion
text.unpack1('m0') decodes strict base64 with nothing to load, and [bytes].pack('m0') encodes. Use the base64 gem's urlsafe_decode64 for base64url.
Additional Resources
- Packed data, in the Ruby documentation.
- String#unpack1, in the Ruby documentation.
