Power-Set Method For Ruby Hash

# The Array power set is stolen from http://snippets.dzone.com/posts/show/3524
class Array
  # Returns the "power set" for this Array. This means that an array with all
  # subsets of the array's elements will be returned.
  def power_set
    # the power set line is stolen from http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
    inject([[]]){|c,y|r=[];c.each{|i|r<<i;r<<i+[y]};r}
  end
end

class Hash
  def power_set
    # Returns the "power set" for this Hash. This means that a array with hashes of all
    # subsets of the hash's (key => value) pairs will be returned.
    # Example:
    # >> {:feedback_type=>"", :language_code=>"", :comment=>""}.power_set
    #
    # [{}, {:comment=>""}, {:language_code=>""}, {:language_code=>"", :comment=>""}, {:feedback_type=>""}, {:feedback_type=>"", :comment=>""}, {:feedback_type=>"", :language_code=>""}, {:feedback_type=>"", :language_code=>"", :comment=>""}]

    hash_to_array = self.to_a
    array_power_set = hash_to_array.power_set
    hash_power_set = array_power_set.collect { |pairs| pairs.inject({}) { |hash,pair| hash[pair[0]] = pair[1]; hash } }
    hash_power_set
  end
end

Leave a Reply