Search code examples
rubyhashrandom

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


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


Solution

  • Hash[original_hash.to_a.sample(n)]
    

    For Ruby 2.1,

    original_hash.to_a.sample(n).to_h