1

I have a String s, which in general (but see below) contains several \n, hence can be regarded as multiline string. I want to get the first line (excluding the terminating newline); but if there is no newline at all, the whole string should be returned. Example:

"abc\ndef" -> "abc"
"\ndef"    -> ""
"xyz"      -> "xyz"

My first attempt was

s[/.*(?=\n)/]

but this returns nil if there is no newline in s (because the lookahead expression does not match). I then considered

s[0,s.index("\n")||s.length]

This does work, but I need to mention the variable (s) three times and find this aesthetically unpleasant. Has someone an idea of how to write a concise expression which would work here?

UPDATE: I don't want to scan the whole string (which in general is fairly large). I need it parsed only up the the first newline character.

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • Maybe using the split function would work. – Tristan Mar 24 '21 at 09:55
  • It would split the whole string into lines. In my case, the string is fairly long (a whole file), and I don't need it parsed completely. – user1934428 Mar 24 '21 at 09:57
  • 2
    `s.each_line.first.chomp` – Fravadona Mar 24 '21 at 09:58
  • Does this answer your question? [Reading the first line of a file in Ruby](https://stackoverflow.com/questions/1490138/reading-the-first-line-of-a-file-in-ruby) – iGian Mar 24 '21 at 10:00
  • You can set a limit on split to only split once. – Tristan Mar 24 '21 at 10:00
  • @iGian : No. I don't have a file (i.e. a filename). I'm in a context where I happen to get passed the content of a file as a string and need to read the first line to decide what to do next. – user1934428 Mar 24 '21 at 10:06
  • @Tristan : Could you amend your answer to show how it is done properly? After reading the description of `split`, I tried in irb `"abc\ndef".split(/\n/,1)`, to limit the search to the first match only, but this returned the whole string and did not split at all. – user1934428 Mar 24 '21 at 10:10
  • @user1934428 You should put it to 2 since you want two parts and then take the first with [0]. – Tristan Mar 24 '21 at 10:37
  • @user1934428 the [docs](https://ruby-doc.org/core-2.7.2/String.html#split-method) say _"If limit is 1, the entire string is returned"_. However, since you are only interested in the first line, consider using `each_line.first` as suggested by Fravadona above. – Stefan Mar 24 '21 at 11:42

1 Answers1

1

You can use s.split("\n", 2)[0]. This splits the string at each newline and then takes the first element of the array. We also use the limit parameter so it only splits once.

Tristan
  • 2,000
  • 17
  • 32