#以|为分割点,将arr转换为二维数组 arr = ['1','2','|','3','4','5','6','|','7','8','9','|','10','11','12'] tmp = [] tmp2 = [] for x in arr tmp << x if x != '|' tmp2.push Array.new(tmp) if x == "|" tmp.clear if x == "|" end tmp2.push Array.new(tmp) print tmp2
输出为:
[["1", "2"], ["3", "4", "5", "6"], ["7", "8", "9"], ["10", "11", "12"]]
被ruby的 所有元素都是对象,传的都是引用搞死。。。在tmp2的时候,原来是这么写的 tmp2<<tmp if x == "|"
结果tmp变化了,tmp2中的元素就跟着变化。现在直接Array.new 就好了