如何在 Ruby 中添加数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24035750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:30:27 来源:igfitidea点击:
How can I prepend to an array in Ruby?
提问by nettux
What is the best way to prepend to an array in Ruby. Perhaps something similar to Python's list.insert(0, 'foo')?
在 Ruby 中添加到数组的最佳方法是什么。也许类似于 Python 的东西list.insert(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 数组添加一个元素,并让所有其他元素一起移动。
回答by SteveTurczyn
array = ['b', 'c']
array.unshift('a')
p array
=> ['a', 'b', 'c']
回答by peter
Another way than Steve's answer
史蒂夫的回答之外的另一种方式
array = ['b', 'c']
array = ['a'] + array #["a", "b", "c"]
回答by steenslag
array = ["b", "c"]
array.insert(0, "a", "a") # => ["a", "a", "b", "c"]

