This question already has an answer here:
这个问题已经有了答案:
- What is the easiest way to push an element to the beginning of the array? 5 answers
- 将元素推到数组开头的最简单方法是什么?5个回答
What is the best way to prepend to an array in Ruby. Perhaps something similar to Python's list.insert(0, 'foo')
?
在Ruby中预置数组的最好方法是什么。也许类似于Python的列表。插入(0,“foo”)?
I'd like to be able to add an element to a Ruby array at the 0 position and have all other elements shifted along.
我希望能够将一个元素添加到一个位于0位置的Ruby数组中,并让所有其他元素沿着这条线移动。
3 个解决方案
#1
54
array = ['b', 'c']
array.unshift('a')
p array
=> ['a', 'b', 'c']
#2
4
Another way than Steve's answer
另一种方法比史蒂夫的回答更有效
array = ['b', 'c']
array = ['a'] + array #["a", "b", "c"]
#3
3
array = ["b", "c"]
array.insert(0, "a", "a") # => ["a", "a", "b", "c"]
#1
54
array = ['b', 'c']
array.unshift('a')
p array
=> ['a', 'b', 'c']
#2
4
Another way than Steve's answer
另一种方法比史蒂夫的回答更有效
array = ['b', 'c']
array = ['a'] + array #["a", "b", "c"]
#3
3
array = ["b", "c"]
array.insert(0, "a", "a") # => ["a", "a", "b", "c"]