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?
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 ''
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With