Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby 2.0 how to access element in matrix by coordinate?

Tags:

ruby

matrix

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...

like image 890
hihell Avatar asked Jan 14 '23 17:01

hihell


1 Answers

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)
like image 80
SwiftMango Avatar answered Jan 19 '23 18:01

SwiftMango