I am trying to learn array operations in Ruby but am having trouble modifying a specified element in an array.
For context, I am writing a program which produces a Matrix and then preforms operations on said matrix. The matrix is defined as matix(i,j,val) where i is the number of rows, j is the number of columns, and val is the value which populates each cell of the matrix when it is instantiated.
The matrix is stored in a data variable created by multiple one dimensional arrays as so:
@data = Array.new(i) { Array.new(j) {val} }
I am trying to write a function set(i,j,val) which sets the element at (i,j) to the value stored in val. I am attempting to achieve this through iteration:
_i = 0
@data.each do |sub|
if _i == i
sub[j] = val
end
_i += 1
end
The code should iterate to the ith row in the matrix and change the element in column j. Unfortunately, sub[j] = val does not change the value. How can I change the value of an array at a specified index j?
@data[i][j] || @val? 2) If you're trying to create sparse matrices, you might consider using hashes rather than one-dimensional arrays for the backing storage? This has the added benefit that hashes can be assigned a default value.