How to generate a random string in Ruby
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Generating a random string in Ruby can mean very different things depending on the requirement. Sometimes you need a secure token for authentication, sometimes you just need a quick test value, and sometimes you need a custom character set with predictable length.
Use SecureRandom for Real Tokens
If the string matters for security, use Ruby's standard-library SecureRandom module. It is designed for session tokens, password reset links, invitation codes, and other values that should not be guessable.
These methods solve most real application needs. hex is good when you only need hexadecimal characters, alphanumeric is convenient for mixed letters and numbers, and urlsafe_base64 is useful when the string will appear in a URL or query parameter.
The important point is that SecureRandom is not just convenient. It uses a cryptographically secure random source, which is why it should be preferred over ad hoc solutions for anything exposed to users.
Build a String From a Custom Character Set
Sometimes the output must avoid certain characters or follow a business-specific alphabet. In that case, build the string from an explicit character set.
This gives full control over the allowed characters. For example, you might exclude ambiguous characters such as O, 0, I, and 1 if humans need to read or type the generated code.
A custom set is flexible, but remember that Array#sample is not the same thing as a secure token generator. It is fine for lightweight IDs, demo data, or non-security-sensitive values. It is not the right tool for authentication or secrets.
Generate Predictable Random Data in Tests
For tests, repeatability is often more useful than unpredictability. Ruby's Random object can help when you want the same generated values every run.
Because the random generator is seeded with a fixed number, the output is deterministic. That is useful in tests, fixtures, and tutorials, where stable output makes failures easier to understand.
Wrap the Logic in a Helper
If your application needs random strings in more than one place, a helper method keeps the intent clear.
For custom alphabets, write a helper that accepts the allowed characters:
That makes the code easier to reuse and easier to test than scattering one-off expressions throughout the project.
Pick the Output Format First
Before choosing an implementation, decide what kind of string you actually need:
- secure or non-secure
- fixed length or approximate length
- URL-safe or unrestricted
- full ASCII mix or custom alphabet
Once those constraints are clear, the Ruby code becomes straightforward. Most mistakes come from skipping this design step and grabbing the first random-looking method that seems to work.
A good example is SecureRandom.urlsafe_base64. It is excellent for URL-friendly tokens, but its length does not map one-to-one with the argument the way alphanumeric does. If an exact character count matters, choose the method intentionally rather than assuming every generator behaves the same way.
Common Pitfalls
- Using
randorsamplefor security-sensitive tokens. - Assuming
urlsafe_base64returns exactly the number of characters passed in. - Forgetting to define a custom alphabet when some characters must be excluded.
- Repeating random-string logic in many places instead of wrapping it in a helper.
- Using unpredictable randomness in tests where deterministic output would be easier to debug.
Summary
- Use
SecureRandomwhen the string must be secure. - Use a custom character set when the output format has special rules.
- Use a seeded
Randominstance when tests need repeatable values. - Prefer helper methods over scattered inline string-generation code.
- Choose the generator based on security, length, and character-set requirements.
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.