我有一个来自制表符分隔文件的字符串(带回车符和换行符)
"a\taa\taaa\r\nb\tbb\tbbb\r\nc\tcc\tccc"
我想将此字符串转换为类似
的数组[["a","aa","aaa"],["b","bb","bbb"],["c","cc","ccc"]]
现在我已经.scan(/(.+?)\r\n/)
但我仍然只有
[["a\taa\taaa"],["b\tbb\tbbb"],["c\tcc\tccc"]]
答案 0 :(得分:5)
我倾向于使用CSV#parse
来做这样的事情,因为解析代码很容易理解:
CSV.parse("a\taa\taaa\r\nb\tbb\tbbb\r\nc\tcc\tccc", col_sep: "\t")
=> [["a", "aa", "aaa"], ["b", "bb", "bbb"], ["c", "cc", "ccc"]]
答案 1 :(得分:1)
如何使用String#split
和Array#map
?
s = "a\taa\taaa\r\nb\tbb\tbbb\r\nc\tcc\tccc"
s.split("\r") # split by \r (bigger chunks)
=> ["a\taa\taaa", "\nb\tbb\tbbb", "\nc\tcc\tccc"]
s.split("\r").map { |x| x.split } # Split bigger chunks by spaces (including \t)
=> [["a", "aa", "aaa"], ["b", "bb", "bbb"], ["c", "cc", "ccc"]]