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

Ruby Hash Power-Set (See related posts)

// adds a #power_set method to Hash class

# 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


Comments on this post

adiadi81 posts on Dec 14, 2007 at 17:46
And where do you place this code? I am asking since you are overriding the rails default library.

Thanks

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