0

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

1
  • 1
    Please don't use instance variables where you don't need them. I bet @tmp could be a local variable. Commented Feb 18, 2013 at 14:20

2 Answers 2

1

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"]]]
Sign up to request clarification or add additional context in comments.

1 Comment

One of us didn't understand OPs problem :) (probably me). Thanks for bringing up transpose, thats a nice example!
0

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.

2 Comments

Thank you for your replay and tricks. This work fine with only one row of values. But I don't know how many rows and columns I have (define by user)
Can you please extend your question with another example? Easiest would be with two examples: before and after.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.