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
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 に答える
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 に答える