Boris Stitnicky
Boris Stitnicky

Reputation: 12578

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

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?

Upvotes: 8

Views: 2912

Answers (2)

Jerska
Jerska

Reputation: 12002

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

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

Upvotes: 10

halfelf
halfelf

Reputation: 10107

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

Upvotes: 4

Related Questions