For an e-commerce app, I'm trying to turn a hash of options, each with an array of choices, into an array of hashes representing the combinations of those choices. For example:
# Input:
{ :color => [ "blue", "grey" ],
:size => [ "s", "m", "l" ] }
# Output:
[ { :color => "blue", :size => "s" },
{ :color => "blue", :size => "m" },
{ :color => "blue", :size => "m" },
{ :color => "grey", :size => "s" },
{ :color => "grey", :size => "m" },
{ :color => "grey", :size => "m" } ]
Input may have additional options inside of it with an undetermined number of choices for each one, but it will only ever be nested 1 level deep. Any
shift
instead ofunshift
(which doesn't do anything if no arguments are given). And FWIW in Ruby 2+ you can replace the lastmap
withmap(&:to_h)
, ergo:ary.shift.product(*ary).map(&:to_h)
. – Quinate