2010-11-26 27 views
3

在Ruby中,是否可以使用任何方法来确定对象o是否具有类C作为其类祖先的祖先?Ruby:我们如何确定一个对象o是否具有类C作为它的祖先在类层次结构中?

我给出了一个例子,下面我使用一个假设的方法has_super_class?来完成它。我应该如何在现实中做到这一点?

o = Array.new 
o[0] = 0.5 
o[1] = 1 
o[2] = "This is good" 
o[3] = Hash.new 

o.each do |value| 
    if (value.has_super_class? Numeric) 
    puts "Number" 
    elsif (value.has_super_class? String) 
    puts "String" 
    else 
    puts "Useless" 
    end 
end 

预期输出:

Number 
Number 
String 
Useless 

回答

8

尝试obj.kind_of?(Klassname)

1.kind_of?(Fixnum) => true 
1.kind_of?(Numeric) => true 
.... 
1.kind_of?(Kernel) => true 

kind_of?该方法也具有相同的替代is_a?

如果您要检查的对象只能是类的(直接)实例,使用obj.instance_of?

1.instance_of?(Fixnum) => true 
1.instance_of?(Numeric) => false 
.... 
1.instance_of?(Kernel) => false 

您也可以通过调用ancestors方法对其class列出对象的所有祖先。例如1.class.ancestors为您提供[Fixnum, Integer, Precision, Numeric, Comparable, Object, PP::ObjectMixin, Kernel]

0
o.class.ancestors 

使用列表中,我们可以实现has_super_class?像这样(如singletone法):

def o.has_super_class?(sc) 
    self.class.ancestors.include? sc 
end 
3

只需使用.is_a?

o = [0.5, 1, "This is good", {}] 

o.each do |value| 
    if (value.is_a? Numeric) 
    puts "Number" 
    elsif (value.is_a? String) 
    puts "String" 
    else 
    puts "Useless" 
    end 
end 

# => 
Number 
Number 
String 
Useless 
0

的弧度方式:

1.class.ancestors => [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject] 
1.class <= Fixnum => true 
1.class <= Numeric => true 
1.class >= Numeric => false 
1.class <= Array => nil 

如果你想成为看上它,你可以做这样的事情:

is_a = Proc.new do |obj, ancestor| 
    a = { 
    -1 => "#{ancestor.name} is an ancestor of #{obj}", 
    0 => "#{obj} is a #{ancestor.name}", 
    nil => "#{obj} is not a #{ancestor.name}", 
    } 
    a[obj.class<=>ancestor] 
end 

is_a.call(1, Numeric) => "Numeric is an ancestor of 1" 
is_a.call(1, Array) => "1 is not a Array" 
is_a.call(1, Fixnum) => "1 is a Fixnum" 
相关问题