将数组元素拆分为字符串集

时间:2014-05-13 10:33:34

标签: ruby arrays

我们如何将一条线分成一组字符串 输入

array = ["123 abcd ki98 1090:09 12/1/2098", "678 njiu ji87 1087:90 87/56/90"]

期望的输出

array =[["123", "abcd", "ki98", "1090:09", "12/1/2098"],
["678", "njiu", "ji87", "1087:90", "87/56/90"]]

我已经尝试了

array.each do |line|
  array2 << line.split(' ') # doesnt give what I wanted
  array2 << line.split(/\s+/) # doesnt give me what I wanted
  array2 << line.split/\s+/ # comes with error
  array2 << line.split(/\s+/).inspect # This works but is too slow
end

任何修复此问题的建议 - 刚开始使用ruby。请帮忙。

2 个答案:

答案 0 :(得分:2)

另一种解决方案:

a.flat_map(&:split)

答案 1 :(得分:1)

> a.map(&:split).flatten
# => ["123", "abcd", "ki98", "1090:09", "12/1/2098678", "njiu", "ji87", "1087:90", "87/56/90"] 

修改

如果需要数组数组

array = ["123 abcd ki98 1090:09 12/1/2098", "678 njiu ji87 1087:90 87/56/90"]

array.map &:split
# => [["123", "abcd", "ki98", "1090:09", "12/1/2098"], ["678", "njiu", "ji87", "1087:90", "87/56/90"]