Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 47 additions & 13 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4337,29 +4337,63 @@ class String
end
end

def lines(chomp = true) : Array(String)
# Returns an array of the string split into lines.
#
# Both LF (line feed, `\n`) and CRLF (carriage return line feed, `\r\n`) are
# recognized as line delimiters.
#
# If *chomp* is true, the line separator is removed from the end of each line.
#
# ```
# "hello\nworld\n".lines # => ["hello", "world"]
# "hello\nworld\n".lines(chomp: false) # => ["hello\n", "world\n"]
# "hello\nworld\r\n".lines # => ["hello", "world"]
# "hello\nworld\r\n".lines(chomp: false) # => ["hello\n", "world\r\n"]
# ```
#
# A trailing line feed is not considered starting a final, empty line. The
# empty string does not contain any lines.
#
# ```
# "hellp\n".lines # => ["hellp"]
# "\n".lines # => [""]
# "".lines # => [] of String
# ```
#
# * `#each_line` yields each line without allocating an array
Comment thread
nobodywasishere marked this conversation as resolved.
def lines(chomp : Bool = true) : Array(String)
lines = [] of String
each_line(chomp: chomp) do |line|
lines << line
end
lines
end

# Splits the string after each newline and yields each line to a block.
# Splits the string after each newline and yields each line.
#
# Both LF (line feed, `\n`) and CRLF (carriage return line feed, `\r\n`) are
# recognized as line delimiters.
#
# If *chomp* is true, the line separator is removed from the end of each line.
#
# ```
# haiku = "the first cold shower
# even the monkey seems to want
# a little coat of straw"
# haiku.each_line do |stanza|
# puts stanza
# end
# # output:
# # the first cold shower
# # even the monkey seems to want
# # a little coat of straw
# "hello\nworld".each_line { } # yields "hello", "world"
# "hello\nworld".each_line(chomp: false) { } # yields "hello\n", "world"
# "hello\nworld\r\n".each_line { } # yields "hello", "world"
# "hello\nworld\r\n".each_line(chomp: false) { } # yields "hello\n", "world\r\n"
# ```
def each_line(chomp = true, &block : String ->) : Nil
#
# A trailing line feed is not considered starting a final, empty line. The
# empty string does not contain any lines.
#
# ```
# "hello\n".each_line { } # yields "hello"
# "\n".each_line { } # yields ""
# "".each_line { } # does not yield
# ```
#
# * `#lines` returns an array of lines
Comment thread
nobodywasishere marked this conversation as resolved.
def each_line(chomp : Bool = true, &block : String ->) : Nil
Comment thread
straight-shoota marked this conversation as resolved.
Outdated
return if empty?

offset = 0
Expand Down