我想弄清楚 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
由此提出的两个问题是
- 为什么 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/