ruby .split('\n') not splitting on new line
RubyStringRuby 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")