简体   繁体   English

Ruby / rails数组填充空项

[英]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? 有任何想法吗?

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 '' . 请注意,如果您的初始(子)数组中包含nil ,则会将其替换为空字符串''

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM