开发者

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

开发者 https://www.devze.com 2023-02-18 22:36 出处:网络
I made开发者_开发百科 a Matrix class and I want to use it in various parts of my code. class 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.

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)


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.


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.


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消