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

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Ruby Hash Power-Set

// adds a #power_set method to Hash class

   1  
   2  # The Array power set is stolen from http://snippets.dzone.com/posts/show/3524
   3  class Array
   4    # Returns the "power set" for this Array. This means that an array with all
   5    # subsets of the array's elements will be returned.
   6    def power_set
   7      # the power set line is stolen from http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
   8      inject([[]]){|c,y|r=[];c.each{|i|r<<i;r<<i+[y]};r}
   9    end
  10  end
  11  
  12  class Hash
  13    def power_set
  14      # Returns the "power set" for this Hash. This means that a array with hashes of all
  15      # subsets of the hash's (key => value) pairs will be returned.
  16      # Example:
  17      # >> {:feedback_type=>"", :language_code=>"", :comment=>""}.power_set
  18      #
  19      # [{}, {:comment=>""}, {:language_code=>""}, {:language_code=>"", :comment=>""}, {:feedback_type=>""}, {:feedback_type=>"", :comment=>""}, {:feedback_type=>"", :language_code=>""}, {:feedback_type=>"", :language_code=>"", :comment=>""}]
  20      
  21      hash_to_array = self.to_a
  22      array_power_set = hash_to_array.power_set
  23      hash_power_set = array_power_set.collect { |pairs| pairs.inject({}) { |hash,pair| hash[pair[0]] = pair[1]; hash } }
  24      hash_power_set
  25    end
  26  end
  27  
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS