DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Random Key From Ruby Hash (even Faster)

05.01.2007
| 5401 views |
  • submit to reddit
        I came across <a href="/posts/show/54">baby's code</a> and then <a href="/posts/show/251">aiosup's</a> 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. <a href="http://pqmf.com">More of my ruby here,</a>

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