开发者

Ruby kind_of? and is_a? returning false for a subclass

I'm trying to take advantage of the ruby methods kind_of? and is_a?. As I understand it they are synonyms of one another.

I have an object of class Child. A call to Child.ancestors gives back an array list this [Child, #<Module>, Parent, ...]. However a call to Child.new.is_a?(Parent) or Child.new.kind_of?(Parent) returns false.

Calling Child.ancestors[2].new.is_a?(Parent) also returns false. I can't seem to figure out why this would be considering calling Parent.new.is_a?(Parent) returns true as it clearly should.

These cl开发者_JAVA技巧asses all eventually descend from ActiveResource::Base if that has anything to do with it.

class Parent < ActiveRecord::Base
  include MyModule 
  def self.my_method(obj) 
    if obj.is_a?(Parent) 
      puts 'Hello' 
    end
  end
end

class Child < Parent
  def my_method
    self.class.my_method(self)
  end
end

a = Child.new 
a.my_method


class Parent
  def self.my_method(obj)
    if obj.is_a?(Parent)
      puts 'IS A PARENT'
    else
      puts 'IS NOT A PARENT'
    end
  end
end

class Child < Parent
  def my_method
    self.class.my_method(self)
  end
end

a = Child.new
a.my_method

Note I dropped the AR and included module, but the above prints out "IS A PARENT" for me. Ruby 1.8.7 on osx.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜