在数组中的空索引处插入值.如何编写更短或更模块化的代码?

Dan*_*ram 2 ruby arrays

我有以下代码,它采用带有不同长度数组的2d数组,并将值0附加到每个索引,直到所有数组的长度相同.

这段代码可以写得更短,更高效和模块化吗?

a = [[1,7],[2,3],[5,1,2],[3],[1],[]]

l = a.map(&:length).max 
a2 = a.each{|e| e.push(Array.new(l - e.length, 0) )}
a2.each{|e| e.flatten!}

#=> [[1, 7, 0], [2, 3, 0], [5, 1, 2], [3, 0, 0], [1, 0, 0], [0, 0, 0]]
Run Code Online (Sandbox Code Playgroud)

UPDATE

因为基于编写代码本身的简单性,我觉得无法对目前给出的两个答案给出一个公认的答案,所以我决定根据代码运行速度的效率来奖励它.

100 test cases running code block 10000 times.

#My Code:
#average run time of test case -> 0.24267sec
#standard deviation -> 0.00735sec

#Stefan’s Code:
#average run time of test case -> 0.06389sec
#standard deviation -> 0.00756sec

#steenslag’s Code:
#average run time of test case -> 0.0577sec
#standard deviation -> 0.00413sec
Run Code Online (Sandbox Code Playgroud)

测试是在相同的条件下使用我制作的自定义编写的ruby计时器类进行的,并且只是相对于彼此以及我运行它们的糟糕的2010-macbookpro.

Ste*_*fan 5

另一种选择Array#fill:

l = a.map(&:length).max
a.each { |e| e.fill(0, e.length...l) }

a #=> [[1, 7, 0], [2, 3, 0], [5, 1, 2], [3, 0, 0], [1, 0, 0], [0, 0, 0]]
Run Code Online (Sandbox Code Playgroud)