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?
Why would you open the class to redefine a method that already exists ?
class Matrix
public :"[]=", :set_element, :set_component
end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With