Ruby - Array#<< 之间的区别和数组#push [英] Ruby - Difference between Array#<< and Array#push

查看:26
本文介绍了Ruby - Array#<< 之间的区别和数组#push的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过检查 Ruby 1.9.3 的文档,Array#<<和 Array#push 旨在实现将元素追加到当前数组的末尾.但是,两者之间似乎存在细微差别.

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]

尝试使用#<<而是给出各种错误,具体取决于它是否与点运算符和/或括号一起使用.

Attempting to use #<< instead gives various errors, depending on whether it's used with the dot operator and/or parentheses.

为什么#<<不像#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.

<< 接受单个参数,并将其推送到数组的末尾.

<< accepts a single argument, and pushes it onto the end of the array.

push 另一方面,接受一个或多个参数,将它们全部推到最后.

push, on the other hand, accepts one or more arguments, pushing them all onto the end.

<< 仅接受单个对象的事实就是您看到错误的原因.

The fact that << only accepts a single object is why you're seeing the error.

这篇关于Ruby - Array#&lt;&lt; 之间的区别和数组#push的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆