来自Ruby中的数组散列的所有可能的组合

前端之家收集整理的这篇文章主要介绍了来自Ruby中的数组散列的所有可能的组合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我拥有的:

假设我有一个这样的哈希,各种值属于一个参数.

a = {}
a[:bitrate] = ["100","500","1000"]
a[:fps] = ["15","30"]
a[:qp] = ["20","30"]

我需要的:

我需要一些迭代地获得这些值的所有可能组合的方式,所以使用所有参数/值对:

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

…在每个可能的组合中调用块.我如何定义foo?

我(可能)不需要:

现在,我知道这个:Combine array of array into all possible combinations,forward only,in Ruby,建议像:

a.first.product(*a[1..-1]).map(&:join)

但是,这仅适用于数组中的值和数组,我需要参考参数的名称.

解决方法

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)

你会得到

[{:bitrate=>"100",:fps=>"15",:qp=>"20"},{:bitrate=>"100",:qp=>"30"},:fps=>"30",{:bitrate=>"500",{:bitrate=>"1000",:qp=>"30"}]

您还可以在您的哈希中添加新的密钥.

a = {}
a[:bitrate] = ["100","30"]
a[:bw] = [true,false]

product_hash(a)

#=>
[{:bitrate=>"100",:qp=>"20",:bw=>true},:bw=>false},:qp=>"30",:bw=>false}]
原文链接:https://www.f2er.com/ruby/272521.html

猜你在找的Ruby相关文章