Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove empty lines from String#each_line #15149

Open
straight-shoota opened this issue Nov 4, 2024 · 2 comments
Open

Remove empty lines from String#each_line #15149

straight-shoota opened this issue Nov 4, 2024 · 2 comments

Comments

@straight-shoota
Copy link
Member

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.

@ysbaddaden
Copy link
Contributor

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

@straight-shoota
Copy link
Member Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants