我正确地扩展这个内置的ruby类吗

我正确地扩展这个内置的ruby类吗

本文介绍了我正确地扩展这个内置的ruby类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的rails应用程序在lib / matrix.rb我已经输入以下代码来扩展内置的Matrix类:

 模块矩阵

需要'matrix'

class Matrix
def symmetric?
如果不是方形,返回false?
(0 ... row_size).each do | i |
(0 .. i).each do | j |
return false if self [i,j]!= self [j,i]
end
end
true
end

cholesky_factor
raise ArgumentError,必须提供对称矩阵,除非对称?
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] = val
end
end
end
Matrix [* l]
end
end
end

这是在rails应用程序中向现有类添加方法的正确方法吗?



编辑1:提供额外资讯



如果在视图页面中输入以下测试代码,只有在我删除了lib / matrix.rb文件

 <%require'matrix'%& 

<%

m = Matrix [
[0,0],
[1,1]
]

%>

<%= m.column(0)%>

否则会出现错误:

 未定义方法`[]'for Matrix:模块

当我尝试扩展类时,我消除了内置的Matrix类的默认方法。有没有办法解决这个错误?

解决方案

这里不需要'matrix'。谁使用你的代码(rails应用程序在你的情况下),应该使用require'matrix'


In my rails app in lib/matrix.rb I have entered the following code to extend the inbuilt Matrix class:

module Matrix

  require '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

Is this the correct way to add methods to an existing class within the rails app? Should I have the require matrix line there?

EDIT 1: Additional info provided

I have now removed the require 'matrix' line.

If I type the following test code in a view page, it only works if I delete my lib/matrix.rb file:

<% require 'matrix' %>

<%

m = Matrix[
   [0,0],
   [1,1]
   ]

%>

<%= m.column(0) %>

Otherwise it gives the error:

undefined method `[]' for Matrix:Module

It appears that I am eliminating the default methods of the built in Matrix class when I try to extend the class. Is there a way around this error?

解决方案

no you should not have to require 'matrix' here. Whoever uses your code(rails app in your case), should use require 'matrix'

这篇关于我正确地扩展这个内置的ruby类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:18