Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate random mixed letters and numbers in Ruby

Tags:

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
like image 354
Ninja2k Avatar asked Dec 15 '22 12:12

Ninja2k


1 Answers

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.

like image 100
danh Avatar answered Mar 01 '23 23:03

danh