我想创建一个固定大小的数组,并且这个数组的默认元素已经从另一个数组中填充了,假设我有以下方法:
有没有更容易的方法在ruby中实现这个?像扩展我已经有的数组大小并用nil对象填充。
def fixed_array(size, other)
array = Array.new(size)
other.each_with_index { |x, i| array[i] = x }
array
end
那么我可以像这样使用该方法:
fixed_array(5, [1, 2, 3])
我将获得
[1, 2, 3, nil, nil]
有没有更容易的方法在ruby中实现这个?像扩展我已经有的数组大小并用nil对象填充。