Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class (Type) checking

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.

like image 989
sawa Avatar asked Feb 08 '12 21:02

sawa


People also ask

What is Python type checking?

Python is a dynamically typed language. This means that the Python interpreter does type checking only as code runs, and that the type of a variable is allowed to change over its lifetime.

What is type checking in TypeScript?

TypeScript type check is used to validate the type of any variable at runtime. Type checking has proven to be a good feature for most JavaScript developers. We will start with the most basic library provided by TypeScript, which will directly validate the type of single variables in the code.

How does a type check work?

A language is typed if the compiler rejects some programs as not being well-formed, based on the expected types of values that appear to be used during computation. In a typed language, the compiler includes a type checker that determines whether the program is well-formed (also: well-typed).

What are type hints?

Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.


1 Answers

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

like image 67
Ed S. Avatar answered Oct 05 '22 23:10

Ed S.