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

29
我想创建一个固定大小的数组,并且这个数组的默认元素已经从另一个数组中填充了,假设我有以下方法:
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对象填充。

1
你想要一个新的数组,还是扩展现有的数组?哪个? - sawa
8个回答

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

这只能针对特定的索引吗? - Tanay Sharma

12
5.times.collect{|i| other[i]}
 => [1, 2, 3, nil, nil] 

5

有没有更容易的方法在 Ruby 中实现这个功能? 比如通过添加 nil 对象来扩展我已经拥有的数组的当前大小?

是的,您可以通过使用 Array#[]= 方法设置最后一个元素来扩展当前数组:

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

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

3

和@xaxxon的回答类似,但更加简洁:

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

或者

(0..4).map {|x| other[x]}

(使用三个点)(0...5) - Oli Crt

3
a = [1, 2, 3]
b = a.dup
Array.new(5){b.shift} # => [1, 2, 3, nil, nil]

或者

a = [1, 2, 3]
b = Array.new(5)
b[0...a.length] = a
b # => [1, 2, 3, nil, nil]

或者

Array.new(5).zip([1, 2, 3]).map(&:last) # => [1, 2, 3, nil, nil]

或者

Array.new(5).zip([1, 2, 3]).transpose.last # => [1, 2, 3, nil, nil]

2
你还可以进行以下操作: (假设other = [1,2,3]
(other+[nil]*5).first(5)
=> [1, 2, 3, nil, nil]

如果其他是空的,你将得到:
(other+[nil]*5).first(5)
=> [nil, nil, nil, nil]

1
这个答案使用了fill方法。
def fixed_array(size, other, default_element=nil)
  _other = other
  _other.fill(default_element, other.size..size-1)
end

0

这样怎么样?这样就不需要创建新的数组了。

def fixed_array(size, other)
  (size - other.size).times { other << nil }
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接