我拥有的:
假设我有一个这样的哈希,各种值属于一个参数.
a = {} a[:bitrate] = ["100","500","1000"] a[:fps] = ["15","30"] a[:qp] = ["20","30"]@H_301_5@我需要的:
我需要一些迭代地获得这些值的所有可能组合的方式,所以使用所有参数/值对:
bitrate = 100,fps = 15,qp = 20
bitrate = 500,qp = 30
> …参数(即键)的数量和值的数量(即值数组的长度)不是预先知道的.理想情况下,我会做一些类似的事情:
a.foo do |ret| puts ret.keys # => ["bitrate","fps","qp"] puts ret.values # => ["100","15","20"] end@H_301_5@…在每个可能的组合中调用块.我如何定义foo?
我(可能)不需要:
现在,我知道这个:Combine array of array into all possible combinations,forward only,in Ruby,建议像:
a.first.product(*a[1..-1]).map(&:join)@H_301_5@但是,这仅适用于数组中的值和数组,我需要参考参数的名称.
解决方法
a = {} a[:bitrate] = ["100","30"] def product_hash(hsh) attrs = hsh.values keys = hsh.keys product = attrs[0].product(*attrs[1..-1]) product.map{ |p| Hash[keys.zip p] } end product_hash(a)@H_301_5@你会得到
[{:bitrate=>"100",:fps=>"15",:qp=>"20"},{:bitrate=>"100",:qp=>"30"},:fps=>"30",{:bitrate=>"500",{:bitrate=>"1000",:qp=>"30"}]@H_301_5@您还可以在您的哈希中添加新的密钥.
a = {} a[:bitrate] = ["100","30"] a[:bw] = [true,false] product_hash(a) #=> [{:bitrate=>"100",:qp=>"20",:bw=>true},:bw=>false},:qp=>"30",:bw=>false}]@H_301_5@