Skip to content

Commit 4ef9167

Browse files
makenowjustRX14
authored andcommittedMar 9, 2018
Improve String#pretty_print output by splitting newline (#5750)
Like Ruby's `pp`, String#pretty_print splits its content by newline and shows each lines with joining `+` operator. I believe this improves readability against large multiline string on `p`.
1 parent 5a189cb commit 4ef9167

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed
 

Diff for: ‎spec/std/string_spec.cr

+7
Original file line numberDiff line numberDiff line change
@@ -1494,6 +1494,13 @@ describe "String" do
14941494
"\u{1f48e}".inspect_unquoted.should eq %(\u{1F48E})
14951495
end
14961496

1497+
it "does pretty_inspect" do
1498+
"a".pretty_inspect.should eq(%("a"))
1499+
"hello\nworld".pretty_inspect.should eq(%("hello\\n" + "world"))
1500+
"hello\nworld".pretty_inspect(width: 9).should eq(%("hello\\n" +\n"world"))
1501+
"hello\nworld\n".pretty_inspect(width: 9).should eq(%("hello\\n" +\n"world\\n"))
1502+
end
1503+
14971504
it "does *" do
14981505
str = "foo" * 10
14991506
str.bytesize.should eq(30)

Diff for: ‎src/string.cr

+17-1
Original file line numberDiff line numberDiff line change
@@ -3831,7 +3831,23 @@ class String
38313831

38323832
# Pretty prints `self` into the given printer.
38333833
def pretty_print(pp : PrettyPrint) : Nil
3834-
pp.text(inspect)
3834+
printed_bytesize = 0
3835+
pp.group do
3836+
split('\n') do |part|
3837+
printed_bytesize += part.bytesize
3838+
if printed_bytesize != bytesize
3839+
printed_bytesize += 1 # == "\n".bytesize
3840+
pp.text("\"")
3841+
pp.text(part.inspect_unquoted)
3842+
pp.text("\\n\"")
3843+
break if printed_bytesize == bytesize
3844+
pp.text(" +")
3845+
pp.breakable
3846+
else
3847+
pp.text(part.inspect)
3848+
end
3849+
end
3850+
end
38353851
end
38363852

38373853
# Returns a representation of `self` using character escapes for special characters and wrapped in quotes.

0 commit comments

Comments
 (0)
Please sign in to comment.