4

Imagine I have an array like:

[["abc","zxy","fgh"], ["fgj","xxy"], ["eee", "aaa", "bbb", "hhh"]]

I want to have an array that would contain all the elements for each subarray, plus appended empty (or default) items until the length of the largest subarray.

For the example, this would be:

[["abc","zxy","fgh", ""], ["fgj","xxy", "", ""], ["eee", "aaa", "bbb", "hhh"]]

Any ideas?

2 Answers 2

5

Map each array to a new array with an initial size of the max of all the arrays, falling back to a default value when there is no value.

array = [["abc","zxy","fgh"], ["fgj","xxy"], ["eee", "aaa", "bbb", "hhh"]]
max_size = array.map(&:size).max
array.map { |a| Array.new(max_size) { |i| a[i] || '' } }
#=> [["abc", "zxy", "fgh", ""],
#    ["fgj", "xxy", "", ""],
#    ["eee", "aaa", "bbb", "hhh"]]

Note that if your initial (sub)arrays have a nil in them, this will replace it with an empty string ''.

Sign up to request clarification or add additional context in comments.

Comments

4

Simply:

array=[["abc","zxy","fgh"], ["fgj","xxy"], ["eee", "aaa", "bbb", "hhh"]]
array.map {|sub_array| sub_array.in_groups_of(4, "").flatten }

#=> [["abc", "zxy", "fgh", ""],
#    ["fgj", "xxy", "", ""],
#    ["eee", "aaa", "bbb", "hhh"]] 

3 Comments

For future visitors, note that in_groups_of is not in Ruby Core and requires ActiveSupport.
True. But the question is tagged with ruby-on-rails as well.
yes, I actually asked because I knew of in_groups_of but was at a loss at how to use it effectively.

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.