我曾在使用扩展类中轨,特别是扩展Matrix类一些困难 - 我还要求与此相关的一些问题:两个扩展类 - 一个工程和其他没有
Am I extending this inbuilt ruby class correctly
Using custom functions in rails app
Where do I put this matrix class in my rails app
一般的答案已在轨已经出现自动加载3. 然而,当我伸出 '数学'新功能的工作,当我延长'矩阵'的新功能不起作用 - 即使我以相同的方式对待他们
我已经尝试了很多迭代和更改模块名称,要求自动加载,但这里是我的最新密钥文件:
application.rb中:
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'matrix'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module SimpleFixed
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# **I have tried all these autoload variants**
# config.autoload_paths += %W(#{config.root}/extras)
# config.autoload_paths += %W(#{config.root}/lib)
# config.autoload_paths += Dir["#{config.root}/lib/**/"]
# config.autoload_paths << "#{Rails.root}/lib"
config.autoload_paths << "#{::Rails.root.to_s}/lib" # <-- set path
require "extend_matrix" # <-- forcibly load your matrix extension
*other standard code here*
的lib/extend_math.rb
module Math
class << self
def cube_it(num)
num**3
end
def add_five(num)
num+5
end
end
end
的lib/extend_matrix.rb
module Extend_matrix **An error is raised if I call this Matrix**
class Matrix
def symmetric?
return false if not square?
(0 ... row_size).each do |i|
(0 .. i).each do |j|
return false if self[i,j] != self[j,i]
end
end
true
end
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum)/l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
end
我的看法页:
<%= Math.add_five(6) %> **works*
<%= Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor %> **doesn't work**
难道是因为数学是在Ruby模块,但矩阵是一类?如果是这样,我该如何纠正?
谢谢!这一直困扰着我一个星期,你的解决方案是完美的。我希望我能给你更多的观点。 – Zakoff 2012-02-04 10:48:04
非常感谢您的反馈,仅此一项就值得您想要额外提供的任何观点;-) – mliebelt 2012-02-04 11:02:04