5

When calling set_element on an instance of the Matrix class I get the following error

NoMethodError: private method ‘set_element’ called for Matrix[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]:Matrix

But set_element is listed under public instance methods in the documentation

Matrix#set_element

Also, set_element is an alias for []=(i, j, v) and using this method I get the following error

ArgumentError: wrong number of arguments (3 for 2)

Doesn't make any sense, any help is appreciated.

Ruby 1.9.2 p180

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Ram
  • 423
  • 4
  • 7
  • You're not the first person surprised by Matrix: http://stackoverflow.com/questions/6064902/copy-inheritance-of-a-ruby-singleton-class-core-std-lib . I don't know whether that question will help you though. – Andrew Grimm Jun 24 '11 at 05:29
  • See also http://stackoverflow.com/questions/7214367/using-ruby-1-9-2-with-rubymine-and-matrix – Marc-André Lafortune Sep 10 '11 at 18:21

2 Answers2

7

You can simply make the setter functions public, possibly in your own class (or at Matrix itself):

class SetableMatrix < Matrix
  public :"[]=", :set_element, :set_component
end
theldoria
  • 378
  • 9
  • 22
1

The documentation is incorrect. If you look at the matrix.rb file from 1.9.1, you'll see this:

def []=(i, j, v)
  @rows[i][j] = v
end
alias set_element []=
alias set_component []=
private :[]=, :set_element, :set_component

So the three methods are there but they are explicitly set as private.

A bit of quick experimentation indicates that a lot of the methods in the documentation are, in fact, private. There is a big block of documentation at the top of the man page that lists what are, apparently, supposed to be the available methods; that list doesn't match the list that rdoc has generated so there is some confusion.

I get the impression that instances of Matrix are meant to be immutable just like Fixnum and Number.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • There is a some discussion about this topic here http://www.ruby-forum.com/topic/161792 – Ram Jun 24 '11 at 05:55
  • @Ram: But I don't see any justification for the immutability of Matrix. Seems unnecessarily cumbersome to me. I suppose you could just copy `matrix.rb` and remove the `private` stuff, it looks like a simple array of arrays internally. – mu is too short Jun 24 '11 at 06:09