@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Generate random password-ish string in Ruby



For generating string of random numbers, SecureRandom#random_number can be used. However, it doesn't guarantee returning fixed length of string.

irb(main):011:0> loop { s = SecureRandom.random_number(10**10).to_s; break "#{s} is #{s.size} length of string" if s.size != 10 }
=> "99743850 is 8 length of string"

It might be better to exclude some symbol characters like whitespace, single quote, double quote and backslash because they make output string hard to see.

# symbols without whitespace, single quote, double quote, and backslash
def generate_random_symbols_without_some_chars(length)
  chars = 0.upto(127).map(&:chr).select{|c| c.match?(/[[:print:]]/) } - [' ', "'", '"', '\\'] - (0..9).to_a.map(&:to_s) - ('a'..'z').to_a - ('A'..'Z').to_a
  length.times.map{ chars.shuffle.first }.join