hihell
hihell

Reputation: 946

ruby 2.0 how to access element in matrix by coordinate?

I'm new to ruby, but here is the problem. Say I have a matrix, and I need to modify a element at 1,2

mm = Matrix.build(2,4) {0}
mm[1][2] = 404

but this will rise error message

ArgumentError: wrong number of arguments (1 for 2)
from /Users/xxxxxx/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/matrix.rb:314:in `[]'
from (irb):11
from /Users/xxxxxx/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'

I have checked ruby doc, but didn't find any answer, sorry to ask such a stupid question...

Upvotes: 4

Views: 2368

Answers (1)

SwiftMango
SwiftMango

Reputation: 15294

Get element:

mm[1,2] #output 0

Set element:

No method can do that. Matrix is immutable object and cannot be changed (which is, IMHO, not so optimal). You can either copy the matrix by each to an array, change the element, and convert back, or use monkey patch

class Matrix
  def []=(i, j, x)
    @rows[i][j] = x
  end
end
mm[1,2] = 404

Or if you don't want to monkey patch or want to be a bit hacky (although does not look good):

mm.send(:[]=, 1, 2, 404)

Upvotes: 9

Related Questions