owgitt
owgitt

Reputation: 323

How to get the data from line number n to last line from a multi-line string in ruby?

I am executing the following curl request in ruby:

cmd="curl --silent --insecure -i -X GET -u \"local\username:password\" \"https://example.com/Console/Changes\""
response = `cmd`

It is resulting in the following output:

enter image description here

From the above output it seems to be the response variable contains a multi-line string value. Just to confirm, I am trying to print the type of 'response' variable here:

puts response.class

Output here is:

String

How to extract header info and the json body separately from the above response?

Upvotes: 1

Views: 229

Answers (1)

fphilipe
fphilipe

Reputation: 10054

There's better ways to do HTTP requests in Ruby, e.g. using the standard library's Net::HTTP.

Having said that, I'll answer your question.

The HTTP standard specifies that the header and the body are separated by an empty line containing just a CRLF (\r\n). Each line of the header also ends with a CRLF. Thus, we can simply split the response at the first occurrence of two CRLF, i.e. at the string "\r\n\r\n".

Since this sequence might also appear in the body, we need to specify that we want our split to have at most 2 elements.

header, body = response.split("\r\n\r\n", 2)

Note though that with this the last header line will not end in "\r\n", but that shouldn't be a problem. The technically more correct version would be to split at "\r\n" followed by a "\r\n". That way we don't strip the trailing "\r\n" when splitting. This can be done with a regular expression using a look-behind:

header, body = response.split(/(?<=\r\n)\r\n/, 2)

The answer to your question in the title is a bit different though:

How to get the data from line number n to last line from a multi-line string in ruby?

response.lines[n..].join

(Before Ruby 2.6 the range needs to be specified as n..-1.)

Upvotes: 1

Related Questions