Ruby / rails array fill empty items

Imagine I have an array like:

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

      

I want to have an array that will contain all the elements for each subarray, plus the added empty (or default) elements up to the length of the largest subarray.

For example, this would be:

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

      

Any ideas?

+3
arrays ruby ruby-on-rails


source to share


2 answers


Just:



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

      

+4


source to share


Map each array to a new array with an initial size of max. of all arrays, reverting to the default 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 original (sub) arrays have them in them nil

, this will replace it with an empty string ''

.

+4


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics