如何在Ruby中将字符串分隔为嵌套数组中的许多元素

时间:2017-01-23 14:16:52

标签: arrays ruby string

我有一个来自制表符分隔文件的字符串(带回车符和换行符)

"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"]]

2 个答案:

答案 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#splitArray#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"]]