generate a random string in ruby

To generate a random string in Ruby, you can use the SecureRandom module which comes with Ruby's standard library.

If you want to generate a random string that is purely alphabetic, you can use the following code:

main.rb
require 'securerandom'

random_string = SecureRandom.alphanumeric(10)
70 chars
4 lines

This will generate a random string that is 10 characters long and consists of uppercase and lowercase letters and numbers.

If you want to generate a random string that is alphanumeric but excludes symbols, you can modify the code as follows:

main.rb
require 'securerandom'

random_string = SecureRandom.hex(10)
61 chars
4 lines

This will generate a random string that is 10 characters long and consists of hexadecimal characters (0-9, A-F).

You can adjust the length of the string by changing the number argument passed to alphanumeric or hex.

gistlibby LogSnag