Ruby Class#new - Why is `new` a private method?

瘦欲@ 提交于 2020-01-31 19:06:05

问题


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)

回答1:


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.

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.

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:

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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/5380648/ruby-classnew-why-is-new-a-private-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!