覆盖数组的前n个元素?

时间:2014-02-28 02:41:41

标签: ruby

这是我的情景:

a = ["","","","","","","","","",""]  #10 elements. Need not always be blank.
b = ["a","b","c","d"]

我想修改a,使n的第一个a元素替换为b的元素n = b.size()

a = ["a","b","c","d","","","","","",""]

那么,是否有像a.replace(b)这样简单的东西减去截断?

另一种方法是将a.size() - b.size()个元素追加到b

1 个答案:

答案 0 :(得分:2)

您可以使用切片:

a[0, 4] = b

或动态长度:

a[0, b.length] = b