Creating a Random Name Generator in Ruby

A random name generator is a very basic program to make that also has some practical use if you ever need to come up with names. Creating one can help newer programmers better understand file I/O and how to utilise randomness.

Creating the Generator

Before you start programming you need three different lists of names, one for male, one for female and another for last names. Download the lists here and be sure to insert them in the folder for this project.

First define a method that will contain the generator. Inside that method the first thing you should do is define two variables, first name and last name and set them both to nil for now. After that prompt the user for what kind of name they want.

def random_name
   first_name = nil
   last_name = nil
   puts "Do you want a Male or Female name?"
   choice = gets.chomp()

Now you need to pick a random name. Start by opening the appropriate text file using “File.foreach(“filename”)”, this will open up the file and iterate through each line. Use string interpolation to select the correct text file based on the user’s choice.

File.foreach("#{choice}-names.txt")

The program can read through each line now but it still needs to be able to randomly select a name. Add the .each_with_index method to end of the previous bit of code, it will go through and number each line. Next use a “do” statement that will assign one of the names in the text file to the first name variable.

     File.foreach("#{choice}-names.txt").each_with_index do |name, number|
     first_name = name if rand < 1.0/(number+1)
end

This will go through each line of the text file and select one randomly based upon its numbering. After you do this you will need to repeat the process with the text file containing last names.

    File.foreach("last-names.txt").each_with_index do |name, number|
    last_name = name if rand < 1.0/(number+1)
end

Lastly you just need to print out the randomly generated name, end the method and then call it.

    print "Your randomly generated name is: #{first_name} #{last_name}"
end
random_name

Further Suggestions

To add some additional complexity to the generator try adding in the ability to choose how many names to generate when the program runs. You could also make a fantasy themed version of the program which lets the user pick from lists of fantasy names that they want like dwarven and elven.

Have Fun!

Download the above source code here.

If you have any comments or questions email them to me at nick@crumbsofcode.com.