Ruby Class#new - 为什么“new”是私有方法?
我创建了一个 Matrix 类,我想在代码的各个部分使用它。
class Matrix
def initialize(x, y, v=0)
@matrix = Array.new
(0..y).each do |j|
@matrix[j] = Array.new
(0..x).each do |i|
@matrix[j][i] = v
end
end
end
end
当此代码与使用它的代码包含在同一类中时,一切都会正常运行。
当我将此代码移至 lib/matrix.rb 并需要它时,出现以下错误:
./phylograph:30:in `block in run': private method `new' called for Matrix:Class (NoMethodError)
I made a Matrix class and I want to use it in various parts of my code.
class Matrix
def initialize(x, y, v=0)
@matrix = Array.new
(0..y).each do |j|
@matrix[j] = Array.new
(0..x).each do |i|
@matrix[j][i] = v
end
end
end
end
When this code is included in the same class as the code that uses it, everything runs fine.
When I move this code to lib/matrix.rb
and require it, I get the following error:
./phylograph:30:in `block in run': private method `new' called for Matrix:Class (NoMethodError)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我记得,Matrix 是一个纯粹的函数类;它的对象是不可变的,并且简单地创建一个新的 Matrix 对象通常是无用的,因为 API 没有任何可变操作。
因此,新的 Matrix 对象是由 API 创建的,该 API 在用户级别不使用 new 。
这是作者做出的设计决定。
更新:OIC,您无意使用标准库 Matrix 类。因此,从技术上讲,上述是您问题的原因,但对我来说,直接说:
As I recall,
Matrix
is a purely functional class; its objects are immutable, and simply creating a newMatrix
object is normally useless as the API doesn't have any mutable operations.So, new
Matrix
objects are created by an API that just doesn't usenew
at the user level.It's a design decision made by the author.
Update: OIC, you had no intention of using the standard library Matrix class. So the above is technically the reason for your problem but it would have been more helpful for me to just say:
这是因为 Matrix 是标准 ruby 库中的一个类,请尝试给出您的类有不同的名称或将其放入模块中。
It's because Matrix is a class from the standard ruby library, try giving your class a different name or put it inside a module.
至于为什么只有当您将其移动到 lib/matrix.rb 时该错误才会咬您:
在移动它之前,您的代码中没有
require 'matrix'
,所以你没有加载矩阵标准库。但是,当您移动它并在代码中添加require 'matrix'
时,您就加载了矩阵标准库。这就是为什么在编写库时,建议您仅使一个文件对其他文件可见代码。想象一下,如果矩阵库有其他代码可见的其他文件,问题会有多严重!
As for why the bug only bit you when you moved it to
lib/matrix.rb
:Before you moved it, you didn't have
require 'matrix'
in your code, so you didn't load the matrix standard library. But when you moved it, and addedrequire 'matrix'
in your code, you loaded the matrix standard library.This is why, when writing libraries, you're advised to only make one file visible to other code. Imagine how much worse the problem would be if the
matrix
library had other files visible to other code!