Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

matrix

I understood it that Ruby stdlib Matrix is not modifiable, that is, for eg.

m = Matrix.zero( 3, 4 )

one cannot write

m[0, 1] = 7

But I would like to do it so much... I can do it with awkward programming, such as

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 cheating, such as

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

, but I wonder, this has to be a problem that people encounter all the time. Is there some standard, customary way of doing this, without having to rape the class using #send method?

like image 439
Boris Stitnicky Avatar asked Oct 02 '12 02:10

Boris Stitnicky


2 Answers

Why would you open the class to redefine a method that already exists ?

class Matrix
  public :"[]=", :set_element, :set_component
end
like image 189
Jerska Avatar answered Oct 19 '22 04:10

Jerska


You can open the class and def your own method to do this:

class Matrix
  def []=(i, j, x)
    @rows[i][j] = x
  end
end
like image 44
halfelf Avatar answered Oct 19 '22 05:10

halfelf