I'm looking to extract n random key-value pairs from a hash.
相关问题
- facebook error invalid key hash for some devices
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- Unity - Get Random Color at Spawning
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- why 48 bit seed in util Random class?
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- Bcrypt vs Hash in laravel
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
:To sample multiple hash elements, @sawa's answer leverages
Array#to_h
:Note that, as @cadlac mentions,
hsh.to_a.sample.to_h
won't work as expected. It will raisebecause
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:PS: not looking for upvotes, only adding it as an explanation for people newer to Ruby.
One way to accomplish this:
Than call this to get random array sample of the k/v pair:
or this to not hard-code the arrays length:
Example:
For Ruby 2.1,
If your sample has only one element, you could use this:
Or if your sample contains more than one element, use this:
I don't know of such method. Still you can do something like:
If you need to sample more than one element the code will have to be a bit more complicated.
EDIT: to get key value pairs instead of only the value you can do something like: