ruby .split('\n') not splitting on new line

RubyString

Ruby Problem Overview


Why does this string not split on each "\n"? (RUBY)

"ADVERTISING [7310]\n\t\tIRS NUMBER:\t\t\t\t061340408\n\t\tSTATE OF INCORPORATION:\t\t\tDE\n\t\tFISCAL YEAR END:\t\t\t0331\n\n\tFILING VALUES:\n\t\tFORM TYPE:\t\t10-Q\n\t\tSEC ACT:\t\t1934 Act\n\t".split('\n')
>> ["ADVERTISING [7310]\n\t\tIRS NUMBER:\t\t\t\t061340408\n\t\tSTATE OF INCORPORATION:\t\t\tDE\n\t\tFISCAL YEAR END:\t\t\t0331\n\n\tFILING VALUES:\n\t\tFORM TYPE:\t\t10-Q\n\t\tSEC ACT:\t\t1934 Act\n\t"]

Ruby Solutions


Solution 1 - Ruby

You need .split("\n"). String interpolation is needed to properly interpret the new line, and double quotes are one way to do that.

Solution 2 - Ruby

In Ruby single quotes around a string means that escape characters are not interpreted. Unlike in C, where single quotes denote a single character. In this case '\n' is actually equivalent to "\\n".

So if you want to split on \n you need to change your code to use double quotes.

.split("\n")

Solution 3 - Ruby

Ruby has the methods String#each_line and String#lines

returns an enum: http://www.ruby-doc.org/core-1.9.3/String.html#method-i-each_line

returns an array: http://www.ruby-doc.org/core-2.1.2/String.html#method-i-lines

I didn't test it against your scenario but I bet it will work better than manually choosing the newline chars.

Solution 4 - Ruby

Or a regular expression

.split(/\n/)

Solution 5 - Ruby

You can't use single quotes for this:

"ADVERTISING [7310]\n\t\tIRS NUMBER:\t\t\t\t061340408\n\t\tSTATE OF INCORPORATION:\t\t\tDE\n\t\tFISCAL YEAR END:\t\t\t0331\n\n\tFILING VALUES:\n\t\tFORM TYPE:\t\t10-Q\n\t\tSEC ACT:\t\t1934 Act\n\t".split("\n")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2012677View Question on Stackoverflow
Solution 1 - RubyMoriView Answer on Stackoverflow
Solution 2 - RubyjbrView Answer on Stackoverflow
Solution 3 - Ruby23inhouseView Answer on Stackoverflow
Solution 4 - RubyMark SwardstromView Answer on Stackoverflow
Solution 5 - RubyfotanusView Answer on Stackoverflow