The Crystal Programming Language Forum

Default class display and to_s(io : IO) definition

In order to validate an algorithm in test phase, I want to display the ID of the classes used, and also their formatted content.
So, after defining the method to_s(io: IO) to display the formatted content of a given class, I create a new method (say class_id) to retrieve the default display of the class name and ID with the method object_id.
This works well of course, but at the same time, raises a question in my mind: is the creation of the class_id method really necessary, or in other words, is there a way to call the default display method of a class after defining to_s(io: IO)?
Thanks

Does inspect give you what you’re looking for?

Call super or previous_def, I guess.

Could you share some code? It would be easier to understand.

Here is a code snippet to illustrate my need that I finally satisfied from your suggestions. So I’m sharing what I came up with.

require "bit_array"
 
class Gene
  property bits
  private getter size, offset
 
  def initialize(@size : Int32, @offset : Int32 = 0)
    @bits = BitArray.new(@size)
    @bits.each_with_index { |_, i| @bits[i] = Random.rand(0..1) == 0 ? false : true }
  end
end
 
alias Genes = Hash(Symbol, Gene)
 
class Chromosome
  @genes = Genes.new
  getter genes
end

As the class names indicate, this is a short extract of a genetic algorithm and to validate and debug/check its progress, I want to display both the Id of the chromosome, the Id, name and variables specific to each gene and its final value, resulting from a specific decoding calculation.
For example, for a chromosome with 2 genes :

#<Chromosome:0x7f30c12243e0> gp_kc=#<Gene:0x7f30c1220900>5:5=01000->8->15->20 gp_kq=#<Gene:0x7f30c12208d0>5:5=11101->29->22->27

we have, after the name and ID of each, the instance variables @size and @offset (5:5), then the bitarray and its successive decoding leading to the final values 20 and 27.

@jhass Using inspect gives only a partial solution, as decoding steps and final value are missing.

@asterite previous_def does not work (“Error: there is no previous definition of ‘to_s’”), but super is the way to go.

So I defined the to_s methods,

for Gene as :

def to_s(io : IO)
      super
      io << size << ":" << offset << "=" << bits << "->" << bits.to_i << "->" << bits.to_i.to_bin << "->" << value
end

and for Chromosome as :

def to_s(io : IO)
    super
    genes.each do |gk, gv|
       io << "%7s=%-48s" % [gk, gv]
    end
end

to obtain the desired results as above.
Thanks.

You might try .to_json, but you’ll need to add include JSON::Serializable to your class(es).