Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 265
Austin Richardson Avatar asked Jul 27 '26 22:07

Austin Richardson


1 Answers

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.

like image 65
DigitalRoss Avatar answered Jul 31 '26 20:07

DigitalRoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!