All possible combinations from a hash of arrays in Ruby

后端 未结 4 2005
忘掉有多难
忘掉有多难 2021-02-05 08:01

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[:f         


        
4条回答
  •  旧巷少年郎
    2021-02-05 08:31

    I believe fl00r's answer is almost perfect but has a drawback. It assumes that hsh.values and hsh.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:

    def product_hash(hsh)
      keys  = hsh.keys
      attrs = keys.map { |key| hsh[key] }
      product = attrs[0].product(*attrs[1..-1])
      product.map{ |p| Hash[keys.zip p] }
    end
    

    But fl00r can correct me if I'm wrong.

提交回复
热议问题