Ruby Class#new-为什么"new"是私有方法? [英] Ruby Class#new - Why is `new` a private method?

查看:102
本文介绍了Ruby Class#new-为什么"new"是私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个Matrix类,想在代码的各个部分中使用它.

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.

当我将此代码移到lib/matrix.rb并需要它时,出现以下错误:

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)

推荐答案

我记得,Matrix纯粹是

As I recall, Matrix is a purely functional class; its objects are immutable, and simply creating a new Matrix object is normally useless as the API doesn't have any mutable operations.

因此,新的Matrix对象由仅在用户级别不使用new的API创建.

So, new Matrix objects are created by an API that just doesn't use new at the user level.

这是作者做出的设计决定.

It's a design decision made by the author.

更新:OIC,您无意使用标准库Matrix类.因此,从技术上讲,以上是您遇到问题的原因,但是对我来说,说:

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标准冲突 相同名称的库类.

Your definition of Matrix is clashing with the Ruby Standard Library class of the same name.

这篇关于Ruby Class#new-为什么"new"是私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆