条件超过对象的类型

时间:2016-12-24 08:23:26

标签: crystal-lang

我需要使用基于对象类型/类的简单if语句。

我有一个自定义Array类和一个Matrix类。 Array类的元素没有number_of_cols属性

def method(other)
  if self.is_a?(Array)
    c = self.class.zeros(shape[0], shape[1])
  elsif self.is_a?(Matrix)
    c = self.class.zeros(number_of_rows, other.number_of_cols)
  end
end

然而,在运行时,我收到一个错误:

undefined method 'number_of_cols' for Array

这就是为什么我有这个if语句。 我还在self.responds_to?(:number_of_cols)中尝试elsif,但同样的错误。

我总是可以制作两种方法,每种类型一种,但我也想了解为什么在有is_a?responds_to?这样的专用帮助器时这不起作用以避免这些问题

1 个答案:

答案 0 :(得分:2)

您正在致电ReadProcessMemory/WriteProcessMemory,但未确保other.number_of_colsother,只有Matrix是一个。