How to change a matrix (Ruby matrix class std-lib)?

I realized that the Ruby stdlib matrix is ​​not modified, i.e., for example,

m = Matrix.zero( 3, 4 )

you can not write

m[0, 1] = 7

But I would like to do it so much ... I can do it with inconvenient programming, for example

def modify_value_in_a_matrix( matrix, row, col, newval )
  ary = (0...m.row_size).map{ |i| m.row i }.map( &:to_a )
  ary[row][col] = newval
  Matrix[ *ary ]
end

... or with a hoax, for example

Matrix.send :[]=, 0, 1, 7

but I wonder, it should be a problem that people face all the time. Is there any standard, common way to do this without having to rape the class using the #send method?

+5
source share
2 answers

You can open the class and define your own method for this:

class Matrix
  def []=(i, j, x)
    @rows[i][j] = x
  end
end
+3
source

Why should you open a class to override an existing method?

class Matrix
  public :"[]=", :set_element, :set_component
end
+8
source

All Articles