Abuzed
Abuzed

Reputation: 27

split and merge multidimensional array ruby

I have a multidimensional array like that:

original_array[0] = Array(20 elements) # Titles
original_array[1] = Array(20 elements) # Values

I have splited this array ever 10 columns:

@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

Now I will merge to this result:

# 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

What the best way to do this? Any help will be highly appreciated

Upvotes: 0

Views: 1857

Answers (2)

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31428

Here's a more functional approach

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

Upvotes: 1

reto
reto

Reputation: 16732

Something like:

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?

Please note, sometimes these nice functional programming paradigms lead to awkward solutions. If something 'imperatively' programmed is a bit longer but much clearer go for it.

Upvotes: 0

Related Questions