Ruby: How to determine if an object o has class C as its ancestor in the class hierarchy?

In Ruby, is it possible to determine whether an object o has class C as its ancestor in the class hierarchy using any method?

I gave an example below, where I use a hypothetical method has_super_class?to execute it. How should I really do this?

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

Expected Result:

Number
Number
String
Useless
+3
source share
4 answers

Try obj.kind_of?(Klassname):

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

The method kind_of?also has an identical alternative is_a?.

If you want to check if an object is an (direct) instance of a class, use 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].

+8

.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
+3
o.class.ancestors

, has_super_class? ( ):

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

The radius of the path:

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

If you want you to be interested in this, you can do something like this:

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"
0
source

Source: https://habr.com/ru/post/1777053/


All Articles