How to generate a random String in Ruby?
Last Updated :
08 Apr, 2024
In this article, we will learn how to generate a random String in Ruby.
Approach to generate a random String in Ruby:
When you need to generate a random alphanumeric string of a specified length in Ruby, you have a couple of options.
If you are using Ruby version >= 2.5, Ruby, you can simply go with:
SecureRandom.alphanumeric(length)
For older versions, you can utilize a little numeric conversion hack: integer#to_s method accepts an argument representing the base.
For example:
13.to_s(2) # = “1101” in binary
13.to_s(16) # = “d” in hex
Custom String generator:
Ruby
class Generator
# Define CHARSET by merging character ranges
# and converting them to arrays
CHARSET = [('0'..'9'), ('a'..'z'), ('A'..'Z')].flat_map(&:to_a)
# Constructor method to initialize
# the Generator object
def initialize(length:, exceptions: [])
@length = length
# Create allowed_charset by removing
# exception characters from CHARSET
@allowed_charset = CHARSET - exceptions
end
# Method to generate a random string of
# specified length using the allowed character set
def perform
# Generate an array of length @length,
# where each element is a random
# character from @allowed_charset
random_string = Array.new(@length) { @allowed_charset.sample }
# Join the array elements to form
# a single string and return it
random_string.join
end
end
# Create an instance of Generator with
# length 10 and exceptions for characters
# that might be confused
generator = Generator.new(length: 10, exceptions: ['1', 'I', 'l', '0', 'o', 'O'])
# Generate and print a single random string
puts generator.perform
# Create another instance of Generator
# with the same specifications
better_generator = Generator.new(length: 10, exceptions: ['1', 'I', 'l', '0', 'o', 'O'])
# Generate an array of 3 random
# strings and print them
puts (1..3).map { better_generator.perform }
OutputYLVvEEqmYi
ngTc6i6H5e
L4x2uxhnWJ
RQVZQxVasQ
Share your thoughts in the comments
Please Login to comment...