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

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

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

5条回答
  •  情深已故
    2020-12-14 15:09

    Hash[original_hash.to_a.sample(n)]
    

    For Ruby 2.1,

    original_hash.to_a.sample(n).to_h
    

提交回复
热议问题