对象类型的条件

Condition over object's type

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

我有一个自定义数组 class 和一个矩阵 class。数组 class 的元素没有 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 语句的原因。 我也在 elsif 中尝试了 self.responds_to?(:number_of_cols) 但同样的错误。

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

您正在调用 other.number_of_cols,但您无法确保 other 是一个 Matrix,只能确保 self 是一个。