Ruby Hash Extensions

As I mentioned before, one of the nice things about Ruby is its malleability. Here are a couple extensions to the Ruby Hash object:

class ::Hash
  def random
    return self.keys[rand(self.size)]

  def byValue(subKey)
      if subKey
        self.sort_by {|key, value| value[subKey]}.reverse
        self.sort_by {|key, value| value}.reverse

Simply, Hash.random will now return a random hash key. Hash.byValue will sort the hash by value. Hash.byValue(‘priority’) will sort a Hash-of-Hashes by the value of the named sub-key. TIMTOWTDI, for sure.

This entry was posted in Coding, Linuxy and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *