0

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?

2
  • We need to see your sample input and what you want your output to look like. Commented Mar 24, 2014 at 19:44
  • 1) Why not use an actual 2-d matrix to store values, and add a getter which returns @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. Commented Mar 24, 2014 at 19:58

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

I was unaware Ruby supported that notation. This is defiantly the most intuitive way to solve the problem.
@Adam, you can chain almost anything together in Ruby. In this case, the second set of brackets act on the return value of the first set of brackets (everything is evaluated from left to right).
Adam, just to be clear, this is not "notation". When Zach speaks of the [] method, that's precisely what he means: Array#[]. Have a read, and don't be confused by the unusual way that method is written. If it were instead Array#get_element, you would write @data.get_element(i).get_element(j), which means (@data.get_element(i)).get_element(j). If @data were a 2x3 (row x column) matrix, it might look like this: [[1,2,3], [4,5,6]], in which case @data[1][2] = (@data[1])[2] = ([4,5,6])[2] = 5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.