Iterating type variables
One of the most common use cases for type introspection is that of iterating over a type's instance variables. The simplest example of this would be adding a #to_h
method to an object that returns Hash
using the type's instance variables for the key/values. This would look like this:
class Foo getter id : Int32 = 1 getter name : String = "Jim" getter? active : Bool = true def to_h { "id" => @id, "name" => @name, "active" => @active, } end end pp Foo.new.to_h
Which, when executed, would print the following:
{"id" => 1, "name" => "Jim", "active" => true}
However, this is less than ideal because...