Over a million developers have joined DZone.

Return A Random Value By Weight In Ruby

·
Should be self explanatory. In the example below, "dog" will be returned 30 times as often as "parrot", and twice as often as "cat".


def rand_from_weighted_hash hash
  total_weight = hash.inject(0) { |sum,(weight,v)| sum+weight }
  running_weight = 0
  n = rand*total_weight
  hash.each do |weight,v|
    return v if n > running_weight && n <= running_weight+weight
    running_weight += weight
  end
end

def random_pet
  pet_likelihoods = {
    30 => "dog",
    15 => "cat",
    4 => "goldfish",
    1 => "parrot"
  }
  rand_from_weighted_hash(pet_likelihoods)
end

puts random_pet
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}