# To\_s overloading?

**URL:** <https://forum.crystal-lang.org/t/to-s-overloading/5399>\
**Category:** Help & Support\
**Created:** [February 18, 2023, 2:19pm UTC](https://forum.crystal-lang.org/t/to-s-overloading/5399 "2023-02-18T14:19:41Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![hutou](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/hutou/32/1337_2.png) [@hutou](https://forum.crystal-lang.org/u/hutou)\
**Post date:** [February 18, 2023, 2:19pm UTC](https://forum.crystal-lang.org/t/to-s-overloading/5399/1 "2023-02-18T14:19:41Z")

</div>

Is it possible to overload to\_`s(io)` ?  
For example, I’d like to do something like:

```auto
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\>

---

<div class="post-metadata">

**Author:** ![naqvis](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/naqvis/32/906_2.png) [@naqvis](https://forum.crystal-lang.org/u/naqvis)\
**Post date:** [February 18, 2023, 2:36pm UTC](https://forum.crystal-lang.org/t/to-s-overloading/5399/2 "2023-02-18T14:36:03Z")

</div>

Yeah, you can override that.

```crystal
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

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [February 18, 2023, 2:53pm UTC](https://forum.crystal-lang.org/t/to-s-overloading/5399/3 "2023-02-18T14:53:28Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![asterite](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/asterite/32/60_2.png) [@asterite](https://forum.crystal-lang.org/u/asterite)\
**Post date:** [February 18, 2023, 4:40pm UTC](https://forum.crystal-lang.org/t/to-s-overloading/5399/4 "2023-02-18T16:40:49Z")

</div>

> [@hutou](#):
>
> but the output is not what expected.

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.
