Adam Jakiela
Adam Jakiela

Reputation: 2248

Modifying an element in a Ruby array at a specified index?

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?

Upvotes: 0

Views: 843

Answers (1)

Zach Kemp
Zach Kemp

Reputation: 11904

Don't overthink this. Obviously you know what index you need to change, so you can just access them directly by chaining together the [] methods. You don't need iteration for a single value:

@data[i][j] = new_value

Upvotes: 2

Related Questions