Skip to content

Instantly share code, notes, and snippets.

@ctcherry
Created December 2, 2010 22:16
Show Gist options
  • Save ctcherry/726194 to your computer and use it in GitHub Desktop.
Save ctcherry/726194 to your computer and use it in GitHub Desktop.
Hash combinations
# Get array with all of the combinations of key=>value pairs from an input hash, taking 1 at a time when the value of a pair is an array
def attribute_combinations(original_hash)
field_varitions = []
original_hash.each do |key, value|
if value.is_a?(Array)
field_varitions << {:key => key, :values => value}
end
end
return original_hash if field_varitions.empty?
hash_diffs = [{}]
field_varitions.each do |varation_set|
new_hash_diffs = []
varation_values = varation_set[:values]
varation_key = varation_set[:key]
hash_diffs.each do |existing_diff|
varation_values.each do |value|
new_hash_diffs << existing_diff.merge({varation_key => value})
end
end
hash_diffs = new_hash_diffs
end
hash_diffs.collect{|m| original_hash.merge(m)}
end
# INPUT
{:colors=>["red", "green"], :age=>23, :friends=>["bob", "joe", "sam"], :height=>"5'11", :brothers=>["adam", "henry", "steve"]}
# OUTPUT
[{:colors=>"red", :age=>23, :friends=>"bob", :height=>"5'11", :brothers=>"adam"},
{:colors=>"red", :age=>23, :friends=>"bob", :height=>"5'11", :brothers=>"henry"},
{:colors=>"red", :age=>23, :friends=>"bob", :height=>"5'11", :brothers=>"steve"},
{:colors=>"red", :age=>23, :friends=>"joe", :height=>"5'11", :brothers=>"adam"},
{:colors=>"red", :age=>23, :friends=>"joe", :height=>"5'11", :brothers=>"henry"},
{:colors=>"red", :age=>23, :friends=>"joe", :height=>"5'11", :brothers=>"steve"},
{:colors=>"red", :age=>23, :friends=>"sam", :height=>"5'11", :brothers=>"adam"},
{:colors=>"red", :age=>23, :friends=>"sam", :height=>"5'11", :brothers=>"henry"},
{:colors=>"red", :age=>23, :friends=>"sam", :height=>"5'11", :brothers=>"steve"},
{:colors=>"green", :age=>23, :friends=>"bob", :height=>"5'11", :brothers=>"adam"},
{:colors=>"green", :age=>23, :friends=>"bob", :height=>"5'11", :brothers=>"henry"},
{:colors=>"green", :age=>23, :friends=>"bob", :height=>"5'11", :brothers=>"steve"},
{:colors=>"green", :age=>23, :friends=>"joe", :height=>"5'11", :brothers=>"adam"},
{:colors=>"green", :age=>23, :friends=>"joe", :height=>"5'11", :brothers=>"henry"},
{:colors=>"green", :age=>23, :friends=>"joe", :height=>"5'11", :brothers=>"steve"},
{:colors=>"green", :age=>23, :friends=>"sam", :height=>"5'11", :brothers=>"adam"},
{:colors=>"green", :age=>23, :friends=>"sam", :height=>"5'11", :brothers=>"henry"},
{:colors=>"green", :age=>23, :friends=>"sam", :height=>"5'11", :brothers=>"steve"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment