Over a million developers have joined DZone.

Random Key From Ruby Hash (even Faster)

DZone's Guide to

Random Key From Ruby Hash (even Faster)

· ·
Free Resource
I came across baby's code and then aiosup's from 2 years ago, and realized that I like the simplicity of one and the approach of the other. Kudos to both authors, and I found a way to combine the two approaches into one neat mechanism. More of my ruby here,

class Hash
  @keys_not_used = nil

  def random_key
          @keys_not_used = self.dup if (!@keys_not_used or @keys_not_used.size == 0)
	  key = @keys_not_used.keys[rand(@keys_not_used.size)]


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}