Napoleon
Napoleon

Reputation: 1102

Get first lines from string (w/o processing entire string)

I know that

my_str.split("\n").first 

gives me the first line of the string.

But sadly that cuts the entire string into an array. If that string is several MB in size and I only need the first 5 lines then... There's gotta be a better alternative. I could write my own method to process the string character by character but there is probably some better method or even a build-in one for what I need?

Upvotes: 3

Views: 151

Answers (1)

Stefan
Stefan

Reputation: 114248

There's String#each_line:

my_str.each_line.take(5)

Upvotes: 6

Related Questions