ruby - .insert 如何工作?

标签 ruby

我想弄清楚 insert 函数在 Ruby 中的作用。

我已经咨询过 Google 和 ruby​​-doc.com,但解释不足以描述这个(看似)神秘的功能。

这是让我感到困惑的地方:

a = %w{a b c d}
puts a.insert(4, 5)  output = a,b,c,d,5

第一个问题是,为什么没有插入4?

puts a.insert(2,2,6)

输出是:

a
b
2
6
c
d

由此提出的两个问题是

  1. 为什么 2 没有插入两次?
  2. 为什么 2 和 6(看似)随意地放在 b 和 c 之间?

最佳答案

我不确定混淆是什么。来自 Ruby 文档:

ary.insert(index, obj...)  -> ary

Inserts the given values before the element with the given index (which may be negative).

a = %w{ a b c d }
a.insert(2, 99)         #=> ["a", "b", 99, "c", "d"]
a.insert(-2, 1, 2, 3)   #=> ["a", "b", 99, "c", 1, 2, 3, "d"]

因此,a.insert(2, 99)99 插入数组中恰好在数组偏移量 2 之前。请记住,数组的索引从 0 开始,因此是数组中的第三个​​槽。

第二个示例是将数组 [1,2,3] 插入倒数第二个数组槽中,因为负偏移量从数组末尾算起。 -1 是最后一个索引,-2 是倒数第二个。

Array 文档说得很好:

Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array---that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

这些是一般编程中需要学习的非常重要的概念,而不仅仅是在 Ruby 中。

关于ruby - .insert 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462797/

相关文章:

ruby-on-rails - 如何在相同的 Rails 应用程序之间序列化和通信 ActiveRecord 实例?

ruby-on-rails - 如何为特定方法启用猴子补丁?

ruby - 测试变量是否等于两个值之一

ruby - RVM Ruby 安装失败,没有校验和

ruby - Shoes 中实例变量的奇怪行为

ruby - 从外部前置后如何调用原始方法

ruby - 如何使 Ruby 脚本每秒运行一次?

ruby - 有没有一种简单的方法来模拟 Dir::glob?

ruby - 使用 Mongoid 查找集合中的所有文档

ruby-on-rails - 搜索 "/"时出现 Thinking Sphinx 错误