Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

split

ruby

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?

like image 896
Napoleon Avatar asked Apr 24 '26 20:04

Napoleon


1 Answers

There's String#each_line:

my_str.each_line.take(5)
like image 66
Stefan Avatar answered Apr 27 '26 11:04

Stefan