Skip to content
Tags

Secret Santa w/ Ruby

by cory on December 18th, 2007
For our office secret santa pool, I wrote a quick little ruby script to generate the pairings and email each of the people in our office with their result. Here's the salient code:
pool = ["person1@email.address.com",
        "person2@email.address.com",
        "person3@email.address.com"]
        
avail = pool.dup
pairs = []

pool.each do |secret_santa|
  loop do
    index = (rand * avail.length).to_i
    recipient = avail[index]
    unless recipient == secret_santa
      avail.delete_at(index)
      pairs << [secret_santa, recipient]
      break
    end
  end
end
This generates a list of tuples (the variable pairs) that you can then iterate over, emailing out the results. Here's the full code (download here).
#!/usr/bin/ruby
require 'net/smtp'

PRINT_RESULTS = true # Print results to screen?
EMAIL_RESULTS = false # email the results?


pool = ["person1@email.address.com",
        "person2@email.address.com",
        "person3@email.address.com"]
        
avail = pool.dup
pairs = []

pool.each do |secret_santa|
  loop do
    index = (rand * avail.length).to_i
    recipient = avail[index]
    unless recipient == secret_santa
      avail.delete_at(index)
      pairs << [secret_santa, recipient]
      break
    end
  end
end

pairs.each do |secret_santa,recipient| 
  from = "the_north_pole@northpole.np"
  from_alias = "santa"
  to = secret_santa
  to_alias = secret_santa
  
  sbj = "secret santa -- ho ho ho"
  msg = "You are #{secret_santa}. " <<
                  "Your secret santa recipient is: "<<
                  "#{recipient}."
  send_email(from, from_alias, to, to_alias, sbj, msg) if EMAIL_RESULTS
  puts "#{secret_santa}  => #{recipient}" if PRINT_RESULTS
end

def send_email(from, from_alias, to, to_alias, subject, message)
	msg = <
To: #{to_alias} <#{to}>
Subject: #{subject}
	
#{message}
END_OF_MESSAGE
	
   Net::SMTP.start('localhost') do |smtp|
      smtp.send_message msg, from, to
   end
end

From → general, ruby

2 Comments
  1. YeaSayer permalink

    "(rand * avail.length).to_i" should be written as "rand avail.length"

  2. YeaSayer permalink

    "(rand * avail.length).to_i" should be written as "rand avail.length"

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS