generate random string in ruby

To generate a random string in Ruby, you can make use of the SecureRandom module. Specifically, you would use the Base64.urlsafe_encode64 method to generate a random string of a specified length.

Here's an example of how you can generate a 10-character long random string using SecureRandom:

main.rb
require 'securerandom'

random_string = SecureRandom.urlsafe_base64(10)
puts random_string
91 chars
5 lines

The urlsafe_base64 method returns a random string that consists of URL-safe base64 characters. The length of the returned string is the number of bytes specified in the argument to the method (in this case, 10). The resulting string may therefore be slightly longer than 10 characters, since base64 characters use 6 bits per character.

You can change the length of the string by changing the argument passed to the method.

related categories

gistlibby LogSnag