Is there an equivalent to `Array::sample` for hashes?

前端 未结 5 1688
终归单人心
终归单人心 2020-12-14 14:26

I\'m looking to extract n random key-value pairs from a hash.

5条回答
  •  抹茶落季
    2020-12-14 15:05

    One way to accomplish this:

    rank_hash = {"Listen" => 1, "Download" => 60, "Share" => 150, "Purchase" => 700 }
    
    rank_array = rank_hash.to_a
    

    Than call this to get random array sample of the k/v pair:

    rank_array[rand(0..3)]
    

    or this to not hard-code the arrays length:

    rank_array[rand(0..(rank_array.length) -1)]
    

    Example:

    ["Download", 60]
    

提交回复
热议问题