Skip to content

Instantly share code, notes, and snippets.

@jodell
Created March 21, 2010 06:35
Show Gist options
  • Save jodell/339137 to your computer and use it in GitHub Desktop.
Save jodell/339137 to your computer and use it in GitHub Desktop.
# Returns a random item from a hash of key => weight
# -jodell 20100321
def select_weighted(hsh)
# roll randomly on the sum of values
roll = rand(hsh.values.inject(0) { |sum, v| sum += v })
index = 0
hsh.each do |k, v|
index += v
return k if index > roll
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment