红宝石 - 阵列#℃之间的差异;&LT;和阵列#推 [英] Ruby - Difference between Array#<< and Array#push
问题描述
从检查对Ruby 1.9.3,这两个阵列#&LT的文件;&LT;和阵列#推被设计为执行附加的元件,以当前数组的末尾。然而,似乎有在两者之间的细微差别。
From examining the documentation for Ruby 1.9.3, both Array#<< and Array#push were designed to implement appending an element to the end of the current array. However, there seem to be subtle differences between the two.
我所遇到的一种是*运算可用于整个其它数组的内容追加到当前一个,但只与#push
The one I have encountered is that the * operator can be used to append the contents of an entire other array to the current one, but only with #push.
a = [1,2,3]
b = [4,5,6]
a.push *b
=> [1,2,3,4,5,6]
尝试使用#&LT;&LT;而不是给出各种错误,这取决于它的使用点运算符和/或括号使用。
Attempting to use #<< instead gives various errors, depending on whether it's used with the dot operator and/or parentheses.
为什么#&LT;&LT;不行#push做同样的方式吗?一个实际上并不为其他的别名?
Why does #<< not work the same way #push does? Is one not actually an alias for the other?
推荐答案
他们都非常相似,但并不完全相同。
They are very similar, but not identical.
&LT;&LT;
接受一个参数,并推动它到数组的结尾。
<<
accepts a single argument, and pushes it onto the end of the array.
推
,在另一方面,接受一个或多个参数,将它们推到全部结束。
push
, on the other hand, accepts one or more arguments, pushing them all onto the end.
事实上,&LT;&LT;
只接受一个对象就是为什么你看到的错误
The fact that <<
only accepts a single object is why you're seeing the error.
这篇关于红宝石 - 阵列#℃之间的差异;&LT;和阵列#推的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!