Look, coming from Ruby I know if you provide a to_s
method in your classes it’s used when doing string interpolation of object, in: puts " ...#{obj}"
I was trying to figure out (quickly) how to get this behavior in Crystal.
I originally did it like this, just to test the working of my code (not worrying about pretty output).
class XYZ
.....
def to_s()
"(#{a} #{sgn(b)}i #{sgn(c)}j #{sgn(d)}k)\n"
end
private def sgn(n)
n.sign|1 == 1 ? "+ #{n}" : "- #{n.abs}"
end
end
This forced me to explicitly write .to_s
inside: puts " ..."#{xyz.to_s}"
.
Knowing now how to do it below I can just do: puts " ..."#{xyz}"
, like I wanted.
class XYZ
.....
def to_s(io : IO)
io << "(#{a} #{sgn(b)}i #{sgn(c)}j #{sgn(d)}k)\n"
end
private def sgn(n)
n.sign|1 == 1 ? "+ #{n}" : "- #{n.abs}"
end
end
I initially went here here and put to_s
in search bar, which gave me a bunch of choices, and ultimately went here.
This did not show me how to use the method to do what I wanted, or what to do to do what I wanted. So instead (again) of spending too much time trying to figure where to find this in the docs, I simply asked the question here, and got the answer I needed.
I said (as an aside) better documentation is needed, because there were no immediate examples to show me how to do what I wanted (where I looked at).
Documentation for users (and developers) should answer at least 3 questions:
- how to use a method, or do something
- why you should/could do this
- when you should/could do this
I’m not going to rehash here all my reasons and pleadings to improve documentation. See here
The comment was to provide feedback that I tried to use the docs to answer the question before posting it, and didn’t find the answer I needed elsewhere.