Over a million developers have joined DZone.

Random Key From Ruby Hash

·
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
Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}