Ruby
Programming
Code Generation
String Manipulation
Randomization

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.

Browse interview questions

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.

ruby
1require "securerandom"
2
3puts SecureRandom.hex(8)          # 16 hex characters
4puts SecureRandom.alphanumeric(12)
5puts SecureRandom.urlsafe_base64(9)

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.

ruby
1charset = ("A".."Z").to_a + ("0".."9").to_a
2random_code = Array.new(10) { charset.sample }.join
3
4puts random_code

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.

ruby
1rng = Random.new(1234)
2charset = ("a".."z").to_a
3value = Array.new(8) { charset[rng.rand(charset.length)] }.join
4
5puts value

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.

ruby
1require "securerandom"
2
3def generate_token(length = 16)
4  SecureRandom.alphanumeric(length)
5end
6
7puts generate_token
8puts generate_token(24)

For custom alphabets, write a helper that accepts the allowed characters:

ruby
1def random_string(length, charset)
2  Array.new(length) { charset.sample }.join
3end
4
5charset = %w[A B C D E F 2 3 4 5 6 7]
6puts random_string(12, charset)

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 rand or sample for security-sensitive tokens.
  • Assuming urlsafe_base64 returns 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 SecureRandom when the string must be secure.
  • Use a custom character set when the output format has special rules.
  • Use a seeded Random instance 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.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions