Using Ruby 1.9.2 with RubyMine and Matrix

2019-08-08 13:19发布

问题:

I am using ruby 1.9.2-p290 and RubyMine. And i try to use Matrix (require 'matrix'). So, i have few questions.

  • How can i change any value of matrix?

For example:

require 'matrix'
matrix =  Matrix[[1, -2, 3], [3, 4, -5], [2, 4, 1]]
matrix[0, 0] = 5
p matrix

Gives next:

in `<top (required)>': private method `[]=' called for Matrix[[1, -2, 3], [3, 4, -5], [2, 4, 1]]:Matrix (NoMethodError)
from -e:1:in `load'
from -e:1:in `<main>'
  • Is it possible to show me methods for matrix by code completion in RubyMine IDE?
  • What library(s) should i use for matrices? Matrix? Mathn? Something else?

回答1:

Ad 1) I know the documentation says that []= is a public instance method, reality in 1.9.2 does not seem to match that:

matrix.private_methods.grep(/\[\]/) #=> [:[]=]

I see two ways around this. The first is using send to bypass private:

matrix.send(:[]=, 0, 0, 5) #=> 5

The second is going through an array:

m = *matrix
m[0][0] = 5
matrix = Matrix[*m]

If you really wanted to, you could change the visibility of the method:

matrix.class.class_eval { public :[]= }

Note that I don't encourage any of these, the way the class is implemented is a strong hint that the authors consider matrices to be immutable objects.

Ad 2) I don't know RubyMine unfortunately, but the documentation for the Matrix class can be found here.

Ad 3) I haven't had an extensive use for matrices in Ruby yet, but for what I needed them the Matrix class was good enough.



回答2:

Just wanted to supplement Michael's answer:

1) The Matrix library has been designed such that Matrices are immutable, the same way that you can't set the real part of Complex number.

I'm the maintainer of the library (but not the original author). I admit it would probably be useful if they were mutable, though. It's too late to change it for Ruby 1.9.3, but I hope to check about consequences for making them mutable.

3) Another possibility is to check the NArray library.