Skip to content

Instantly share code, notes, and snippets.

@redperadot
Last active August 29, 2015 13:57
Show Gist options
  • Save redperadot/9645216 to your computer and use it in GitHub Desktop.
Save redperadot/9645216 to your computer and use it in GitHub Desktop.
Raffle off items with ruby.
#!/usr/bin/env ruby
#
# raffle.rb - Raffle off items with ruby. Version 0.2
# Made with ❤︎ by [email protected]
#
# To use cd into a directory with a 'tickets.txt'
# file and a 'items.txt' file. Then just run the
# script. Items in the files should be separated
# by new lines.
say = false
## Why Ruby have no titlecase?
class String
def titlecase
title = self.split
title.map do |word|
unless (word.include?("of")) || (word.include?("the")) && (title.first != "the")
word.capitalize
end
end.join(" ")
end
end
## Load files, reformat, and remove duplicates.
abort "Could not find 'tickets.txt' in '#{Dir.getwd}/'" unless File.exists?("tickets.txt") # Look for files.
abort "Could not find 'items.txt' in '#{Dir.getwd}/'" unless File.exists?("items.txt") # Abort if files can't be found.
tickets = IO.readlines("tickets.txt").map(&:downcase).map(&:strip).sort.uniq # Read files, reformat, and remove duplicates.
items = IO.readlines("items.txt").map(&:downcase).map(&:strip).sort.uniq # Reformatting will strip extra whitespace and lowercase everything.
puts "Found #{tickets.count} tickets and #{items.count} items." # Count tickets and items.
abort "Not enough tickets for all the items!" if tickets.count < items.count # Exit if there are not enough tickets.
## Choose winners.
winners = Hash.new
items.each do |item|
winner = tickets.sample # Pick a random ticket.
winner = tickets.sample while winners.include?(winner) # Redraw if winner has already been chosen.
winners[winner] = item # Add winner to list.
end
winners = winners.sort_by { |ticket,item| ticket } # Sort winners by name.
## Build Anticipation
print " Picking from a hat\r"
sleep 1
print " Picking from a hat.\r"
sleep 1
print " Picking from a hat..\r"
sleep 1
print " Picking from a hat...\r"
sleep 1
puts " "
## Print winners to file and screen.
File.open("winners.csv", "w+") do |f| # Open or create winners file.
f.puts("Ticket,Item") # Write head of CSV file.
winners.each { |ticket,item| f.puts("#{ticket.titlecase},#{item}") } # Write winners in CSV format to file.
end
winners.each { |ticket,item| puts "#{ticket.titlecase} has won #{item}."; `say "#{ticket.titlecase} has won!"` if say == true; sleep 0.4 } # Print winners to screen.
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment