Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/rails array fill in empty items

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?

like image 285
mlkmt Avatar asked Jan 14 '23 06:01

mlkmt


1 Answers

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 ''.

like image 169
Andrew Marshall Avatar answered Jan 20 '23 04:01

Andrew Marshall