Project

General

Profile

Actions

Feature #12586

open

Hash#sample

Added by shevegen (Robert A. Heiler) over 8 years ago. Updated over 8 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:76370]

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!

Actions

Also available in: Atom PDF

Like0
Like0