random pronounceable strings in ruby

sometimes its useful to generate random pronounceable strings programmatically. one example is flickr’s upload email address. wordpress does the same; you can post a blog entry via a random (but easy to remember) email address.

here’s a chunk of ruby code that generates those random pronounceable strings. i added numbers at the end too. it doesn’t look so efficient, so maybe you can make it better?

require 'rubygems'
require 'activesupport'
 
class String
  ALPHABET = ('a' .. 'z').to_a
  VOWELS = %w/a e i o u/
  CONSONANTS = ALPHABET - VOWELS
 
  def self.pronounceable syllables = 2
    returning Array.new do |r|
      syllables.times do
        r < < CONSONANTS.rand
        r << VOWELS.rand
        r << ALPHABET.rand
      end
      r << rand(1000)
    end.join
  end
end

examples!

>> String.pronounceable 2
=> "cugril760"
>> String.pronounceable 2
=> "daydab759"
>> String.pronounceable 2
=> "nanrax748"

the output is kinda fun to say out loud. (try it!)

update! changed per visnu’s suggestions


About this entry