Home > Blockchain >  NameError: uninitialized constant Matrix only in rails console
NameError: uninitialized constant Matrix only in rails console

Time:09-20

When I try using Matrix or Vector standard Ruby's classes in Rails 7 app I receive NameError:

rails c
Loading development environment (Rails 7.0.3.1)
[1] pry(main)> Matrix
NameError: uninitialized constant Matrix

Explicit require doesn't help:

[3] pry(main)> require 'matrix'
LoadError: cannot load such file -- matrix

But this is standard Ruby module https://ruby-doc.org/stdlib-3.1.0/libdoc/matrix/rdoc/Matrix.html and when used inside vanila irb (without rails) it works:

irb(main):001:0> Matrix
(irb):1:in `<main>': uninitialized constant Matrix (NameError)
        from /home/oleg/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
        from /home/oleg/.rbenv/versions/3.1.2/bin/irb:25:in `load'
        from /home/oleg/.rbenv/versions/3.1.2/bin/irb:25:in `<main>'
irb(main):002:0> require 'matrix'
=> true
irb(main):003:0> Matrix
=> Matrix

In both cases

ruby --version
ruby 3.1.2p20 (2022-04-12 revision 4491bb740a)  YJIT [x86_64-linux]

I've already used matrices in this project on Rails 4 or 5, but first time tried them after updating to 7 and thus - zeitwerk. Is it even related to zeitwerk?

CodePudding user response:

Matrix was removed from Ruby 3.1.

More info: https://www.ruby-lang.org/en/news/2021/12/25/ruby-3-1-0-released/

You can add it manually or run something like:

$ bundle add matrix
$ bundle install

After that, it should work.

  • Related