-1

私はこれらの配列を持っています:

positions = [[0, 1, 2], [2, 3]] 
values = [[15, 15, 15], [7, 7]]
keys = [1, 4]

keysキーが fromで値が from であるハッシュを作成する必要がありますvalues。値はpositions. If no index is defined,nil` で定義されたインデックスにある必要があり、そのインデックスに追加する必要があります。

3 つの配列には同じ数の要素が含まれています。keysには 2 つの要素、valuestwo、およびpositionstwo があります。それで大丈夫です。

期待される出力:

hash = {1=>[15, 15, 15, nil], 4=>[nil, nil, 7, 7]}
4

4 に答える 4

1

最もきれいではありません..しかし動作します:P

max = positions.flatten.max + 1
pv = positions.zip(values).map { |o| o.transpose.to_h }
h = {}
pv.each_with_index do |v, idx|
  h[keys[idx]] = Array.new(max).map.with_index { |_, i| v[i] }
end

# h
# {1=>[15, 15, 15, nil], 4=>[nil, nil, 7, 7]}

または、より圧縮されているが読みにくいものを好む場合..

keys.zip(positions.zip(values).map { |o| o.transpose.to_h }).reduce({}) do |h, (k, v)|
  h[k] = Array.new(max).map.with_index { |_, i| v[i] }
  h
end
于 2017-04-05T07:34:22.260 に答える
0
new_hash = {}

keys.each_with_index do |key, index|

    new_hash[key] = Array.new(positions.flatten.max + 1)
    value_array = values[index] 
    position_array = positions[index] 
    position_array.each_with_index.map { |element, i| new_hash[key][element] = value_array[i]} 
end 
new_hash

これがうまくいくことを願っています。

于 2017-04-05T07:27:08.570 に答える