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

04.07.2005
| 12623 views |
  • submit to reddit
        Returns a random key from your hash, but won't repeat until it's done every one.  (I was using this to help quiz myself.)
class Hash
  @keys_used = []

  def random_key
    @keys_used = [] if @keys_used.size == self.size
    key = self.keys[rand(self.size)]
    while @keys_used.include?(key)
      key = self.keys[rand(self.size)]
    end
    @keys_used << key
    return key
  end
end