Feature #12586
openHash#sample
Description
Hello.
class Array has .sample method.
I tried to use .sample on a hash, just to return a random element (I needed to
debug this in my key, from a list of hash-kept remote URLs where I will batch
download these files via a ruby script).
To my surprise, class Hash has no .sample. I am not sure why not, perhaps there
is some logical reason, but perhaps it may also have been forgotten?
I am using this code as workaround:
hash = { :cat => 'Tom', :mouse => 'Jerry', :dog => 'Spike'}
hash.to_a.sample(1).to_h # => {:mouse=>"Jerry"}
hash.to_a.sample(1).to_h # => {:cat=>"Tom"}
This works fine. I could also modify class Hash of course but
I rather want to stick to main-ruby (and thus not modify core
classes of ruby if I release my code via gems).
I did not need any argument other than 1 to .sample() since
I only needed to obtain one random hash key-value pair.
If this was already discussed or suggested and rejected, feel
free to close this issue request. Thanks!
Updated by shyouhei (Shyouhei Urabe) over 8 years ago
We looked at this issue at yesterday's developer meeting. I wonder if this is actually useful. The Tom&Jerry example is too simplistic and we at the meeting could not imagine what "a list of hash-kept remote URLs" that the OP says would look like.
Can you show us a more realistic use-case where this feature is useful?