在Ruby中为self赋值

时间:2015-10-31 16:17:58

标签: ruby

我在Ruby中有以下类:

class TOMatrix < Matrix
   def initialize
     self = Matrix.build(8, 8){|r, c| 0}
   end

但是,这给出了错误:

 Cannot assign to a keyword

有谁知道如何实现我的需求?

2 个答案:

答案 0 :(得分:2)

似乎你需要编写一个包装器而不是子类化Matrix(在你的情况下子类化可能会破坏Liskov的替换原则):

require 'matrix'   

class TOMatrix
  def initialize
    @matrix = Matrix.build(8, 8){|r, c| 0}
  end

  def method_missing(*args, &block)
    @matrix.send(*args, &block)
  end

  def respond_to?(method)
    super || @matrix.respond_to?(method)
  end
end

m = TOMatrix.new
m.hermitian? #=> true

答案 1 :(得分:1)

您无法直接更改self的值。你可能想做这样的事情:

class Matrix     # I defined it so that people can test the code right away
    def initialize
        @rows = []
        self
    end

    def build rows = 0, columns = 0    #Use your own version of build instead
                                       # It should modify Matrix instead of returning a new one

        @rows = Array.new(rows, Array.new(columns, 0))
    end
end

class TOMatrix < Matrix
    def initialize
        super.build 8, 8    #Initializes Matrix and calls build on it
    end
end