我有一个像这样的多维数组:
original_array[0] = Array(20 elements) # Titles
original_array[1] = Array(20 elements) # Values
我已将这个数组拆分为10列:
@splited_array = Array.new
@original_array.each do |elem|
@tmp = Array.new
elem.each_slice(10) do |row|
@tmp << row
end
@splited_array << @tmp
end
# Result:
# splited_array[0][0] => labels 1 to 9
# splited_array[0][1] => labels 10 to 19
# splited_array[1][0] => values 1 to 9
# splited_array[1][1] => values 10 to 19
现在我将合并到这个结果:
# splited_array[0][0] => labels 1 to 9
# splited_array[0][1] => values 1 to 9
# splited_array[1][0] => labels 10 to 19
# splited_array[1][1] => values 10 to 19
最好的方法是什么? 任何帮助将受到高度赞赏
答案 0 :(得分:1)
这是一种更实用的方法
original = []
original[0] = %W(aa bb cc dd ee ff gg hh ii jj kk ll mm nn oo pp qq rr ss tt)
original[1] = %W(01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20)
result = original.map {|arr| arr.each_slice(10).to_a}.transpose
=> [[["aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj"], ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"]], [["kk", "ll", "mm", "nn", "oo", "pp", "qq", "rr", "ss", "tt"], ["11", "12", "13", "14", "15", "16", "17", "18", "19", "20"]]]
答案 1 :(得分:0)
类似的东西:
a1 = (1..10).to_a
a2 = ("A".."J").to_a
out = []
current = []
a1.zip(a2) do |a, b|
current << a
current << b
if current.length >= 10
out << current
current = []
end
end
out << current unless current.empty?
请注意,有时这些不错的函数式编程范例会导致尴尬的解决方案。如果“强制性”编程的东西有点长,但要更清楚。