Class (Type) checking

27,417

Solution 1

Here is something you can start with

class Object
  def class_check(tclass)
    return self.kind_of? tclass unless tclass.kind_of? Array
    return false unless self.kind_of? Array
    return false unless length == tclass.length
    zip(tclass).each { | a, b | return false unless a.class_check(b) }
    true
  end
end

It will return true if the classes match and false otherwise.

Calculation of the indices is missing.

Solution 2

is_a? or kind_of? do what you are asking for... though you seem to know that already(?).

Share:
27,417
sawa
Author by

sawa

I have published the following two Ruby gems: dom: You can describe HTML/XML DOM structures in Ruby language seamlessly with other parts of Ruby code. Node embedding is described as method chaining, which avoids unnecessary nesting, and confirms to the Rubyistic coding style. manager: Manager generates a user's manual and a developer's chart simultaneously from a single spec file that contains both kinds of information. More precisely, it is a document generator, source code annotation extracter, source code analyzer, class diagram generator, unit test framework, benchmark measurer for alternative implementations of a feature, all in one. Comments and contributions are welcome. I am preparing a web service that is coming out soon.

Updated on February 09, 2020

Comments

  • sawa
    sawa over 4 years

    Is there a good library (preferably gem) for doing class checking of an object? The difficult part is that I not only want to check the type of a simple object but want to go inside an array or a hash, if any, and check the classes of its components. For example, if I have an object:

    object = [
      "some string",
      4732841,
      [
        "another string",
        {:some_symbol => [1, 2, 3]}
      ],
    ]
    

    I want to be able to check with various levels of detail, and if there is class mismatch, then I want it to return the position in some reasonable way. I don't yet have a clear idea of how the error (class mismatch) format should be, but something like this:

    object.class_check(Array) # => nil (`nil` will mean the class matches)
    object.class_check([String, Fixnum, Array]) # => nil
    object.class_check([String, Integer, Array]) # => nil
    object.class_check([String, String, Array]) # => [1] (This indicates the position of class mismatch)
    object.class_check([String, Fixnum, [Symbol, Hash]) # => [2,0] (meaning type mismatch at object[2][0])
    

    If there is no such library, can someone (show me the direction in which I should) implement this? Probably, I should use kind_of? and recursive definition.