Ruby String Split on "\ t" loses "\ n"

\ t Try splitting this tab-delimited dataset:

171 1000    21  
269 1000    25  
389 1000    40  
1020    1-03    30  1
1058    1-03    30  1
1074    1-03    30  1
200 300     500

(for clarity:)

171\t1000\t21\t\n   
269\t1000\t25\t\n   
389\t1000\t40\t\n
1020\t1-03\t30\t1\n
1058\t1-03\t30\t1\n
1074\t1-03\t30\t1\n
200\t300\t\t500\n

a = text.split(/\n/)
a.each do |i|
  u = i.split(/\t/)
  puts u.size
end

==>
3
3
3
4
4
4
4

The combination \ t \ n, apparently, shaves off the last \ t that I need for further import. How can I get around this? Greetings

Edited: This is what I expected:

4
4
4
4
4
4
4
+4
source share
1 answer

If this is for production, you should use the CSV class , as @DmitryZ noted in the comments. CSV processing has an amazing amount of caveats, and you should not do it manually.

But skip it as an exercise ...


, . .

a = text.split(/\n/), a .

a = [
    171\t1000\t21\t   
    269\t1000\t25\t   
    389\t1000\t40\t
    1020\t1-03\t30\t1
    1058\t1-03\t30\t1
    1074\t1-03\t30\t1
    200\t300\t\t500
]

String # split, " , .", u = i.split(/\t/) , .

, 4 , 4.

u = i.split(/\t/, 4)

, , -1, " [] , , ". CSV.

u = i.split(/\t/, -1)
+7
source

Source: https://habr.com/ru/post/1662439/


All Articles