How to assign value in 4 X 4 array ruby?

Viewed 73

I am creating an array @multi containing four elements, each of which is a 4-element array. In the example below, the class Test has a method assign_values is to be passed two arguments, an array of one or more two-element arrays, [i,j] ("locations") and a value v, meaning that @multi[i][j] should be set equal to v

The method result returns @multi after all unassigned elements have been set equal to '-'

The user input would be the array locations like below:

Alpha_array = [[0,1], [2,3], [3,2]]
Beta_array = [[0,3], [3,1], [1,0]]

And my desired output is

# => [["-", "A", "-", "B"], ["-B", "-", "-", "-"], ["-", "-", "-", "A"], ["-", "B", "A", "-"]]

What I have tried so far

class Test
  def initialize
    @multi = 4.times.map { 4.times.map { '-' } }
  end

  def assign_values array, new_value
    array.each { |element|
      @multi[element[0]][element[1]] = new_value
    }
  end

  def result
    @multi
  end
end

Alpha_array = [[0,1], [2,3], [3,2]]
Beta_array = [[0,3], [3,1], [1,0]]

test = Test.new
test.assign_values(Alpha_array, 'A')
test.assign_values(Beta_array, 'B')

test.result

Output:

# => [["-", "A", "-", "B"], ["-B", "-", "-", "-"], ["-", "-", "-", "A"], ["-", "B", "A", "-"]]

Is there an elegant and efficient way to get the outuput ?

1 Answers
class Test
  attr_reader :result

  def initialize(dim1, dim2)
    @result = Array.new(dim1) { Array.new(dim2, '-') }
  end

  def assign_values(array, new_value)
    array.each { |i,j| @result[i][j] = new_value }
  end
end

test = Test.new(4,4)
test.assign_values([[0,1], [2,3], [3,2]], 'A')
test.assign_values([[0,3], [3,1], [1,0]], 'B')
test.result
  #=> [["-", "A", "-", "B"],
  #    ["B", "-", "-", "-"],
  #    ["-", "-", "-", "A"],
  #    ["-", "B", "A", "-"]]

See Array::new.

Related