To_s overloading?

Is it possible to overload to_s(io) ?
For example, I’d like to do something like:

def to_s(io : IO, type : Symbol? = nil)
  case type
  when :abc
    io << "abc"
  when :xyz
    io << "xyz"
  else
    # normal
    io << "hello"
  end
end

I tried …to_s(STDOUT, :abc) : it “works” (ie it compiles), but the output is not what expected.

…to_s(STDOUT, :abc) # => abc#<IO::FileDescriptor: fd=1>

Yeah, you can override that.

class Foo
  def to_s(type : Symbol)
    String.build do |sb|
      to_s(sb, type) 
    end
  end
  
  def to_s(io : IO, type : Symbol? = nil) : Nil
    case type
    when :abc
      io << "abc"
    when :xyz
      io << "xyz"
    else
      # normal
      io << "hello"
    end
  end
end

f = Foo.new
pp f.to_s # => "hello"
pp f.to_s(:xyz) # => "xyz"
f.to_s(STDOUT, :abc) # => abc

HIH

Another option is use a more descriptive method, leaving #to_s to be a more generic thing.

1 Like

Suggestion: when you say that something doesn’t work as you expected, please show what you expected in addition to the actual behavior. To me the output you showed is what I’d expect.

3 Likes