2010-11-26 28 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" 
相關問題