3

我想从

{'key1' => (1..10) ,
 'key2' => (11..20) , 
'key3' => (21..30)}

[{'key1' => 1, 'key2' => 11, 'key3' => 21},
{'key1' => 1, 'key2' => 11, 'key3' => 22},...
 .
 .
{'key1' => 10, 'key2' => 20, 'key3' => 30}]

如何解决?

4

6 回答 6

4

这里是 :

hsh = {'key1' => (1..10) ,'key2' => (11..20) , 'key3' => (21..30)}
keys = hsh.keys
hsh['key1'].to_a.product(hsh['key2'].to_a,hsh['key3'].to_a).map{|a|Hash[keys.zip(a)]}

# => [{'key1' => 1, 'key2' => 11, 'key3' => 21},
#   {'key1' => 1, 'key2' => 11, 'key3' => 22},...
#   .
#   .
#   {'key1' => 10, 'key2' => 20, 'key3' => 30}]

当您有更多的键时,您也可以将上面的内容编写如下:

hsh = {'key1' => (1..10) ,'key2' => (11..20) , 'key3' => (21..30)}
keys = hsh.keys
array = hsh.values_at(*keys[1..-1]).map(&:to_a)
hsh['key1'].to_a.product(*array).map{|a|Hash[keys.zip(a)]}
于 2013-09-29T14:29:56.967 回答
2

这么多方法......一个吻答案(编辑为扩展到任意数量的键):

s = {'key1' => (1..10), 'key2' => (11..20), 'key3' => (21..30)}
r = []
s.each {|k,v| a = []; (v.to_a).each {|i| a << {k=>i}}; r << a}
result = r.shift
r.each {|e| result = result.product(e).map(&:flatten)}
result
于 2013-09-29T15:27:58.890 回答
2
h = {
  'key1' => (1..10),
  'key2' => (11..20),
  'key3' => (21..30)
}

h.map { |k,v| [k].product(v.to_a) }.transpose.map { |e| Hash[e] }
#=> [{"key1"=>1, "key2"=>11, "key3"=>21},
#    {"key1"=>2, "key2"=>12, "key3"=>22},
#    {"key1"=>3, "key2"=>13, "key3"=>23},
#    {"key1"=>4, "key2"=>14, "key3"=>24},
#    {"key1"=>5, "key2"=>15, "key3"=>25},
#    {"key1"=>6, "key2"=>16, "key3"=>26},
#    {"key1"=>7, "key2"=>17, "key3"=>27},
#    {"key1"=>8, "key2"=>18, "key3"=>28},
#    {"key1"=>9, "key2"=>19, "key3"=>29},
#    {"key1"=>10, "key2"=>20, "key3"=>30}]
于 2013-09-30T15:18:24.470 回答
1
h = {'key1' => (1..10) ,
'key2' => (11..20) , 
'key3' => (21..30)}

arrays = h.values.map(&:to_a).transpose
p arrays.map{|ar| Hash[h.keys.zip(ar)] }
#=> [{"key1"=>1, "key2"=>11, "key3"=>21}, {"key1"=>2, "key2"=>12, "key3"=>22},...
于 2013-09-29T14:38:54.607 回答
1
h = {'key1' => (1..10), 'key2' => (11..20), 'key3' => (21..30)}

编辑1:进行了一些更改,主要是使用inject({})

f,*r = h.map {|k,v| [k].product(v.to_a)}
f.zip(*r).map {|e| e.inject({}) {|h,a| h[a.first] = a.last; h}}

编辑 2:在看到 @Phrogz 对另一个问题的回答中使用 Hash[] 之后:

f,*r = h.map {|k,v| [k].product(v.to_a)}
f.zip(*r).map {|e| Hash[*e.flatten]}
于 2013-09-29T19:06:09.103 回答
0

做同样的懒惰方式:

h = {
  'key1' => (1..10),
  'key2' => (11..20),
  'key3' => (21..30)
}

result = ( 0...h.values.map( &:to_a ).map( &:size ).max ).map do |i|
  Hash.new { |hsh, k| hsh[k] = h[k].to_a[i] }
end

result[1]['key3'] #=> 22
于 2013-10-21T05:12:38.237 回答