Ninja2k
Ninja2k

Reputation: 879

How can I generate random mixed letters and numbers in Ruby

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

Answers (5)

Ryan Angilly
Ryan Angilly

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

danh
danh

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

Neil Slater
Neil Slater

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

xdsemx
xdsemx

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

steenslag
steenslag

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

Related Questions