Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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)]
	  @keys_not_used.delete(key)
          key
  end

end
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}