I\'m looking to extract n random key-value pairs from a hash.
Reading the top ranked answers, I'd go with it depends:
If you want to sample only one element from the hash, @Ivaylo Strandjev's solution only relies on hash lookup and Array#sample:
hsh[hsh.keys.sample]
To sample multiple hash elements, @sawa's answer leverages Array#to_h:
hsh.to_a.sample(n).to_h
Note that, as @cadlac mentions, hsh.to_a.sample.to_h won't work as expected. It will raise
TypeError: wrong element type String at 0 (expected array)
because Array#sample in this case returns just the element array, and not the array containing the element array.
A workaround is his solution, providing an n = 1 as an argument:
hsh.to_a.sample(1).to_h
PS: not looking for upvotes, only adding it as an explanation for people newer to Ruby.