Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Fill Hash with nil values if no values given

I have these arrays:

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

I need to create a hash whose keys are from keys and the values are from values. Values must be at indices defined in positions. If no index is defined,nil` should be added to that index.

The three arrays contain the same number of elements; keys has two elements, values two, and positions two. So it's ok.

Expected output:

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

Upvotes: -1

Views: 893

Answers (4)

user6536560
user6536560

Reputation:

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

I hope this will work.

Upvotes: 0

Ho Man
Ho Man

Reputation: 2345

Not the cleanest.. but works :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]}

or if you prefer a more compressed but less readable one..

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

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Just out of curiosity:

nils = (0..positions.flatten.max).zip([nil]).to_h
keys.zip(positions, values).group_by(&:shift).map do |k, v|
  [k, nils.merge(v.shift.reduce(&:zip).to_h).values]
end.to_h
#ā‡’Ā {1=>[15, 15, 15, nil], 4=>[nil, nil, 7, 7]}

Upvotes: 1

ndnenkov
ndnenkov

Reputation: 36101

Let the zippery begin šŸ¤ (answer to the original question):

row_size = positions.flatten.max.next

rows = positions.zip(values).map do |row_positions, row_values|
  row = Array.new(row_size)
  row_positions.zip(row_values).each_with_object(row) do |(position, value), row|
    row[position] = value
  end
end

keys.zip(rows).to_h # => {1=>[15, 15, 15, nil], 4=>[nil, nil, 7, 7]}

Upvotes: 2

Related Questions