Code Snippet: Ruby Word Masher

Posted by Ryan Baxter Sat, 28 Jul 2007 20:54:00 GMT

I can be extremely indecisive about things. So much, in fact, that I even wrote a script to help me choose a name for this website. Is it strange that a random number generator can make me feel better about making decisions? My wife thinks I’m crazy, but she also calls domain names, donames. Besides, I think there is something novel in a computer choosing a name for itself. Anyway… Given some user input, the code below will read words from a file and then mash them together to provide unique combinations. Here is a words.dat file to help get you started. Happy mashing.

#!/usr/bin/ruby

words = Array.new
i = 0

def mash_words(words, mash_count)
  new_word = ''

  1.upto(mash_count) do
    new_word += words[rand(words.length)]
  end

  return new_word
end

begin
  puts 'How many mashed words would you like to create?'
  word_count = gets.chomp.to_i  

  puts 'How many words would you like to mash?'
  mash_count = gets.chomp.to_i  

  input_file = File.new("words.dat", "r")
  while (line = input_file.gets)    
    words[i] = line.chomp    
    i += 1
  end  

  1.upto(word_count) do    
    puts mash_words(words, mash_count)
  end  

  input_file.close  
rescue => err
  puts "Exception: #{err}"
  err
end
Comments

Leave a response