What I have:
Let's say I have a hash like this, with various values belonging to one parameter.
a = {}
a[:bitrate] = ["100", "500", "1000"]
a[:fps] = ["15", "30"]
a[:qp] = ["20", "30"]
What I need:
I need some way to iteratively get all the possible combinations of these values, so, with all the parameter/value pairs:
bitrate = 100
,fps = 15
,qp = 20
bitrate = 500
,fps = 15
,qp = 30
- ...
The number of parameters (i.e. the keys) and the number of values (i.e. the length of the value arrays) are not known beforehand. Ideally, I'd do something like:
a.foo do |ret|
puts ret.keys # => ["bitrate", "fps", "qp"]
puts ret.values # => ["100", "15", "20"]
end
… where the block is called for each possible combination. How can I define foo
?
What I (probably) don't need:
Now, I know this: Combine array of array into all possible combinations, forward only, in Ruby, suggesting something like:
a.first.product(*a[1..-1]).map(&:join)
But this operates on values and arrays in arrays only, and I need the original reference to the parameter's name.
Just FYI I took fl00r's approach and monkey-patched it. I like it a bit better.
you'll get
You can also add new key to your hash.
I believe fl00r's answer is almost perfect but has a drawback. It assumes that
hsh.values
andhsh.keys
will have a matching order, which as far as I know, is not warrantied. So you will probably need an extra step to ensure that. Maybe something like:But fl00r can correct me if I'm wrong.