gpt4 book ai didi

Ruby:我们如何识别对象 o 在类层次结构中是否有类 C 作为其祖先?

转载 作者:数据小太阳 更新时间:2023-10-29 07:43:35 24 4
gpt4 key购买 nike

在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

最佳答案

尝试obj.kind_of?(类名):

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 方法来列出对象的所有祖先。例如 1.class.ancestors 给你 [Fixnum, Integer, Precision, Numeric, Comparable, Object, PP::ObjectMixin, Kernel]

关于Ruby:我们如何识别对象 o 在类层次结构中是否有类 C 作为其祖先?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4285001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com