Condition over object's type

人走茶凉 提交于 2019-12-24 11:36:39

问题


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.



来源:https://stackoverflow.com/questions/41311609/condition-over-objects-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!