crystal-lang/crystal

Remove empty lines from `String#each_line`

straight-shoota opened this issue · 2 comments

String#each_line splits a string by line separator (LF or CRLF) and yields each individual line. Sometimes only populated lines are interesting, so you want to remove all empty ones. This can be accomplished by manual filtering. But that adds extra complexity to the call site. I think it would be useful to have a parameter remove_empty : Bool similar to String#split. #each_line is essentially a special case variant of #split.

Is there much gain between:

x.each_line(remove_empty: true) do |line|
  # ...
end

x.each_line do |line|
  next if line.empty? # alternative: line.blank?
  # ...
end

Yeah, I suppose there's not much.
But there might be some efficiency gain with String#lines because it avoids overallocating the array upfront.

x.lines(remove_empty: true)

x.lines.reject!(&.empty?)

I suppose it depends on the ratio of empty lines, and whether a particular use case also involves ignoring lines consisting of only whitespace and the like.

Maybe it's not worth it. I just think it would fit well with the analogy of #split which performs the same kind of operation and has remove_empty, so it's easy to assume #each_line would have it as well.