1 2 3 4 5 6 7 8
alphanumerics = [*('0'..'9')] + [*('A'..'Z')] + [*('a'..'z')] (0...25).map { alphanumerics[Kernel.rand(alphanumerics.size)] }.join alphanumerics = [('0'..'9'),('A'..'Z'),('a'..'z')].map {|range| range.to_a}.flatten (0...25).map { alphanumerics[Kernel.rand(alphanumerics.size)] }.join alphanumerics = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a (0...25).map { alphanumerics[Kernel.rand(alphanumerics.size)] }.join
Refactorings
No refactoring yet !
VitalieL
July 3, 2008, July 03, 2008 07:47, permalink
You will need to filter numbers from [58-64] to avoid \,~ chars
1 2 3 4 5 6 7
irb(main):009:0> a = '-'*25 => "-------------------------" irb(main):010:0> 25.times {|x| a[x] = rand(90) + 48} => 25 irb(main):011:0> a => ">Ne~r4[3Skd2\201s6<\\THOD}QYn" irb(main):012:0>
Ryan Bates
July 3, 2008, July 03, 2008 16:02, permalink
In the past I've added a random_string method to the String class which can take a length and array of chars to use. I wouldn't say it's much of an improvement, but some might find it helpful.
1 2 3 4 5 6
class String def self.random_string(length = 8, chars = nil) chars ||= ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a Array.new(length) { chars[rand(chars.size)] }.join end end
Raghu Srinivasan
July 6, 2008, July 06, 2008 19:46, permalink
Here's what I've been using as a library function
1 2 3 4 5
def random_string(length) chars = ("a".."z").to_a + ("0".."9").to_a randomstring = "" 1.upto(length) { |i| randomstring << chars[rand(chars.size-1)] } end
Justin Jones
July 9, 2008, July 09, 2008 20:28, permalink
Just for something a little different :)
1 2
require 'digest/sha1' Digest::SHA1.hexdigest(Time.now.to_s)
So this is kind of trivial but I can't help but think there is a better way. I've included a couple different ways.