Search code examples
rubymatrixaccess-specifier

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


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)

Solution

  • 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.