在Ruby中拆分文本文件两次

0 ruby text file

我有以下文本文件.

bob jones,19,moore reef,yes,no
jenny smith, 21,reef park,yes,yes
any body, 12,somewhere,no,no
Run Code Online (Sandbox Code Playgroud)

我希望每一行都在一个单独的数组中,或者我希望每个数据片段都有单独的数组(例如,name_array,age_array,destination_array等).

我怎么能这样做?

mu *_*ort 5

使用标准库中的CSV解析器加载它:

require 'csv'
a = CSV.open('x.csv').map { |r| r.map(&:strip) }
Run Code Online (Sandbox Code Playgroud)

会给你一个a这样的:

[
    [ "bob jones",   "19", "moore reef", "yes", "no"  ],
    [ "jenny smith", "21", "reef park",  "yes", "yes" ],
    [ "any body",    "12", "somewhere",  "no",  "no"  ]
]
Run Code Online (Sandbox Code Playgroud)

然后你可以b = a.transpose用来翻转行和列来得到这个b:

[
    [ "bob jones", "jenny smith", "any body" ],
    [ "19", "21", "12" ],
    [ "moore reef", "reef park", "somewhere" ],
    [ "yes", "yes", "no" ],
    [ "no", "yes", "no" ]
]
Run Code Online (Sandbox Code Playgroud)

然后从那里你可以根据需要拉出各个数组:

names, ages, destinations, flags1, flags2 = *b
Run Code Online (Sandbox Code Playgroud)

我不得不猜测flags1flags2名字.