简体   繁体   中英

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:

在此处输入图片说明

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?

There's better ways to do HTTP requests in Ruby, eg 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, ie 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 .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM