Skip to content

Instantly share code, notes, and snippets.

@melriffe
Created January 16, 2013 20:29
Show Gist options
  • Save melriffe/4550620 to your computer and use it in GitHub Desktop.
Save melriffe/4550620 to your computer and use it in GitHub Desktop.
Need to do something in an odd, non-standard ratio of time? Say 13 out of 17 times? Use PassFailinator to accomplish this feat!
# Simple class that lets you to define a custom ratio of when to let something
# occur veruses not.
#
# Inspiration: We've all done the 'index % 5 == 0' to act as a gatekeeper to
# some action, typically when creating test data. However, this works find when
# you want a standard occurance rate: half the time, third of the time, 25% of
# the time. I had a need to generate test data 40% (2 out 5) times. I'm not
# smart enough to calculate a mod that would work for me. So I created a brute-
# force method that included a variable, some checking, some incrementing, and
# voila: 40% of the time I was able to create data.
#
# PassFailiantor is the result of generalizing my solution to allow /any/
# ratio: 6 of 50, 7 of 9, 13 of 27, etc. Initialize an instance with the number
# of times you want it to allow within the total number of guesses. For example
#
# gatekeeper = PassFailinator.new(2,5)
# 5.times { puts gatekeeper.allow? }
# => will output two trues, followed by three falses
class PassFailinator
def initialize(allows, guesses)
@counter = 0
@allows, @guesses = allows, guesses
end
def allow?
result = can_allow?
increment_counter
reset_counter
return result
end
private
def can_allow?
@counter < @allows
end
def increment_counter
@counter += 1
end
def reset_counter
@counter = 0 if time_to_reset?
end
def time_to_reset?
@counter == @guesses
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment