Ruby 创建一个固定大小的数组,并用另一个数组填充默认内容?

Ruby 创建一个固定大小的数组,并用另一个数组填充默认内容?,ruby,arrays,Ruby,Arrays,我想创建一个固定大小的数组,其中默认数量的元素已从另一个数组填充,因此假设我有以下方法: 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对

我想创建一个固定大小的数组,其中默认数量的元素已从另一个数组填充,因此假设我有以下方法:

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对象扩展我已经拥有的数组的当前大小

def fixed_array(size, other)  
   Array.new(size) { |i| other[i] }
end
fixed_array(5, [1, 2, 3])
# => [1, 2, 3, nil, nil]

在ruby中有更简单的方法吗?比如用nil对象扩展我已经拥有的数组的当前大小

def fixed_array(size, other)  
   Array.new(size) { |i| other[i] }
end
fixed_array(5, [1, 2, 3])
# => [1, 2, 3, nil, nil]
是的,您可以通过以下方式设置最后一个元素来扩展当前数组:

方法可以如下所示:

def grow(ary, size)
  ary[size-1] = nil if ary.size < size
  ary
end
def增长(ary,大小)
如果ary.size

请注意,这将修改传递的数组。

您还可以执行以下操作: (假设
other=[1,2,3]

如果另一个是[],则得到

(other+[nil]*5).first(5)
=> [nil, nil, nil, nil]

与@xaxxon的答案类似,但更简短:

5.times.map {|x| other[x]}


此答案使用
fill
方法

def fixed_array(size, other, default_element=nil)
  _other = other
  _other.fill(default_element, other.size..size-1)
end

您想要新阵列还是扩展现有阵列?哪一个?这仅适用于特定索引?或
(0…5)
(带三个点)
a = [1, 2, 3]
a[4] = nil # index is zero based
a
# => [1, 2, 3, nil, nil]
def grow(ary, size)
  ary[size-1] = nil if ary.size < size
  ary
end
(other+[nil]*5).first(5)
=> [1, 2, 3, nil, nil]
(other+[nil]*5).first(5)
=> [nil, nil, nil, nil]
5.times.map {|x| other[x]}
(0..4).map {|x| other[x]}
def fixed_array(size, other, default_element=nil)
  _other = other
  _other.fill(default_element, other.size..size-1)
end