[英]Ruby Gemfile gem has different behavior than 'require' 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的依賴項加載。
Ruby Gemfile gem具有與“ require” gem不同的行為
是的,那是因為它們是兩回事 。 向您的Gemfile中添加一個gem並不會取代對require
類的需要,它只會通知bundler
程序運行該程序需要這個gem。 有關Gemfile和Bundler的更多信息,請參見此處 。
我想你在安裝矩陣“寶石” http://rubygems.org/gems/matrix在你的Gemfile。 矩陣類是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模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.