Skip to content

Instantly share code, notes, and snippets.

@voleinikov
Created May 5, 2015 21:54
Show Gist options
  • Save voleinikov/e5d8defcbfa1ff3ac35e to your computer and use it in GitHub Desktop.
Save voleinikov/e5d8defcbfa1ff3ac35e to your computer and use it in GitHub Desktop.
Ruby function to return weighted boolean value
# Given a float weight between 0 and 1, returns true that percentage of the time
# e.g. 10.times { weighted_bool 0.3 } # should return true about 3 times
def weighted_bool true_weight = 0.5
raise ArgumentError.new("Weight must be a positive value less than or equal to 1.0") unless true_weight >= 0 and true_weight <= 1.0
return rand <= true_weight
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment