Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This adds pretty printing to Crystal objects. And now when you do
p obj
that actually pretty printsobj
instead of usinginspect
. The reason for this is that I always find Ruby'spp
better whenever I want to quickly "inspect" an object, so I think pretty printing should be preferred. There's also Elixir, which only hasIO.inspect
which does pretty printing, and that never bothered me.Example:
Output before:
Output after:
I think I prefer the later to be outputted, always (one can do
puts obj.inspect
to get the old behaviour)I'll be honest: I read the papers about pretty printing and did an implementation myself, but then I checked how it was done in Ruby and it was much better. The difference is that Ruby streams directly to the given output whenever possible, while my implementation constructed the whole tree and then outputted. In the end, my implementation consumed a lot of memory... so I decided to first port Ruby's code to Crystal, check if it works, and then try to understand it. Not surprisingly, porting the code was extremely easy! And it worked out of the box. I think I understand now how it works, though the algorithm is pretty complex (if somebody would like to add more comments afterwards, please do so!). As always, I don't know if I should do something about the copyright, the algorithms seem to be public though I'm not so sure about Ruby's code.
Now we'll have
to_s
,inspect
andpretty_print
... maybe we can removeinspect
? Or maybe we can declare it such that it creates a pretty printer that will output everything into a single line and then invokepretty_print
with it? In that way users would only need to overrideto_s
and/orpretty_print
, but neverinspect
. In any case, maybe that can be decided after we merge this PR.