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

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

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

5条回答
  •  眼角桃花
    2020-12-14 15:11

    If your sample has only one element, you could use this:

    sample = h.keys.sample
    h.select { |k,v| k == sample }
    

    Or if your sample contains more than one element, use this:

    n = 2
    sample = h.keys.sample(n)
    h.select { |k,v| sample.include?(k) }
    

提交回复
热议问题