Search code examples
rubymagic-squareruby-hash

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]}

Solution

  • 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]}