Reputation: 879
I have the following code so far, this generates letters only. I am looking to get both letters and numbers
#Generate random 8 digit number and output to file
output = File.new("C:/Users/%user%/Desktop/Strings.txt", "w")
i = 0
while i < 500
randomer = (0...8).map{65.+(rand(26)).chr}.join
output << randomer
output << "\n"
i = i+1
end
output.close
Upvotes: 4
Views: 2556
Reputation: 1647
You can do something like this
i = 0
while i < 500
randomer = (1..8).map { (('a'..'z').to_a + ('0'..'9').to_a)[rand(36)] }.join
output << randomer
output << "\n"
i = i+1
end
output.close
Enjoy.
Upvotes: 2
Reputation: 62676
How about this:
def random_tuple(length)
letters_and_numbers = "abcdefghijklmnopqrstuvwxyz0123456789"
answer = ""
length.times { |i| answer << letters_and_numbers[rand(36)] }
answer
end
output = ""
500.times { |i| output << random_tuple(8) + "\n" }
You could also have the function append the newline, but I think this way is more general.
Upvotes: 3
Reputation: 27207
(('a'..'z').to_a + ('0'..'9').to_a).sample( 8 ).join
This is random, but will not re-use any number/letter, so it does not cover all possible strings.
Upvotes: 3
Reputation: 1209
Use SecureRandom.hex(10)
his generate letters and numbers in 0-9 and a-f
or
SecureRandom.base64.delete('/+=')[0, 8]
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/securerandom/rdoc/SecureRandom.html
Upvotes: 2
Reputation: 80085
All digits and letters are used in base 36:
max = 36**8
500.times.map{ rand(max).to_s(36).rjust(8,'0') } #rjust pads short strings with '0'
Upvotes: 2