Never been to DZone Snippets before?

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

Usefull Additions to the Hash Class (See related posts)

Rename keys and return a duplicate hash, or perform the method and modify the current hash.
Check each value in the hash and return true if they are all empty, otherwise return false.

class Hash
  def rename_key(old_key, new_key)
    return Hash.rename_key(self.dup, old_key, new_key)
  end
  
  def rename_key!(old_key, new_key)
    return Hash.rename_key(self, old_key, new_key)
  end
  
  def all_values_empty?
    self.each_value do |v|
      return false if v and v != ""
    end
    
    return true
  end
  
  private
    def self.rename_key(hsh, old_key, new_key)
      hsh[new_key.to_s] = hsh.delete(old_key.to_s)
      return hsh
    end
end

You need to create an account or log in to post comments to this site.


Click here to browse all 4834 code snippets

Related Posts