Ruby Gemfile gem与'require'gem的行为不同

时间:2014-12-04 17:08:20

标签: ruby-on-rails ruby gem

我在Ruby中使用Matrix库,当我在irb中使用它时,它运行正常:

2.1.5 :001 > require 'matrix'
 => true 
2.1.5 :002 > a=Matrix.build(3,3) { |row,col| row==col ? 0 : 1}
 => Matrix[[0, 1, 1], [1, 0, 1], [1, 1, 0]] 

但是当我从Gemfile中使用它时,行为是不同的:

Loading development environment (Rails 4.1.8)
2.1.5 :001 > a=Matrix.build(3,3) { |row,col| row==col ? 0 : 1 }
NoMethodError: undefined method `build' for Matrix:Module

我检查了一下,我注意到require行为加载了一个类,而Gemfile加载了一个模块:

需要:

2.1.5 :003 > Matrix.class
 => Class 
2.1.5 :004 > Matrix.constants
 => [:EigenvalueDecomposition, :LUPDecomposition, :SELECTORS, :ConversionHelper, :CoercionHelper, :Scalar, :ErrDimensionMismatch, :ErrNotRegular, :ErrOperationNotDefined, :ErrOperationNotImplemented] 

的Gemfile:

2.1.5 :002 > Matrix.class
 => Module 
2.1.5 :003 > Matrix.constants
 => [:VERSION] 

我应该如何在我的Rails项目中包含它?我可以在某处使用require,但我真的宁愿将其作为Gemfile的依赖项加载。

2 个答案:

答案 0 :(得分:1)

  

Ruby Gemfile gem的行为不同于'要求'宝石

是的,那是因为他们是两件不同的事情。向Gemfile添加gem不会取代require类的需要,它只会通知bundler运行程序需要这个gem。有关Gemfile和Bundler的更多信息,请参阅here

答案 1 :(得分:0)

我认为你在gem文件中安装矩阵'gem'http://rubygems.org/gems/matrix。矩阵类是stdlib的一部分,因此您不需要为它安装gem:http://www.ruby-doc.org/stdlib-2.0/libdoc/matrix/rdoc/Matrix.html。但是你确实需要它来使用它。

TL / DR:从你的Gemfile中删除gem'matrix',只需使用require'matrix'来使用stdlib矩阵实现,而不是看似空的'matrix'gem模块。

相关问题