Ruby.split ('\ n') does not break on a new line

Why doesn't this line break into every "\ 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"] 
+67
string ruby
May 6 '13 at 20:06
source share
5 answers

You need .split("\n") . Correct interpretation of a new line requires string interpolation, and double quotation marks are one way to do this.

+141
May 6 '13 at 20:07
source share
— -

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

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

.split("\n")

+35
May 6 '13 at 20:12
source share

Ruby has String#each_line and String#lines methods

returns enumeration: 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 have not tested it against your script, but I'm sure it will work better than manually selecting newline characters.

+15
Jul 24 '14 at 4:12
source share

Or regex

 .split(/\n/) 
+5
Jul 22 '16 at 18:58
source share

You cannot 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") 
+3
May 6 '13 at 20:07
source share



All Articles