Created
December 10, 2012 19:17
-
-
Save partkyle/4252667 to your computer and use it in GitHub Desktop.
secret santa script in ruby with example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'faker' | |
require 'enumerator' | |
class SecretSanta | |
def initialize(data) | |
@data = data | |
end | |
def perform | |
while !valid? | |
@result = nil | |
assign_matches | |
end | |
assign_matches | |
end | |
private | |
def valid? | |
# a user should not be assigned to themselves | |
assign_matches.count { |a,b| a == b } == 0 | |
end | |
def assign_matches | |
@result ||= @data.zip(@data.shuffle) | |
end | |
end | |
class EmailSource | |
include Enumerable | |
def initialize | |
@source = Enumerator.new do |yielder| | |
loop do | |
yielder << Faker::Internet.email | |
end | |
end | |
end | |
def each(&block) | |
@source.each do |email| | |
if block_given? | |
block.call email | |
else | |
yield email | |
end | |
end | |
end | |
end | |
answer = SecretSanta.new(EmailSource.new.take(100)).perform | |
answer.each do |pair| | |
puts pair.inspect | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment