Condition over object's type

2019-08-02 18:54发布

问题:

I need to use a simple if statement based on an object's type/class.

I have a custom Array class and a Matrix class. Elements of the Array class don't have a number_of_cols attribute

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

However, when running this, I get an error:

undefined method 'number_of_cols' for Array

which is exactyle why I have this if statement. I also tried self.responds_to?(:number_of_cols) in the elsif but same error.

I can always make two methods, one per type, but I'd also like to understand why this is not working when there are dedicated helpers like is_a? and responds_to? to avoid these issues.

回答1:

You're calling other.number_of_cols but you haven't ensured that other is a Matrix, only that self is one.