Using Ruby 1.9.2 with RubyMine and Matrix

不问归期 提交于 2019-12-11 11:06:38

问题


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.



来源:https://stackoverflow.com/questions/7214367/using-ruby-1-9-2-with-rubymine-and-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!