-5

请注意 - 这篇文章被用作课堂示例,请不要因为提出如此明显的问题而投反对票

我试图从这个数组中提取第四个值。下面你可以看到我尝试过的几种方法。任何人都可以建议一种可以实现这一目标的方法吗?

    # creating the array
    array = [1, 4, 5, 6, 7, 8, 9]

    # attempted using an index value, which returned 7 instead 6
    array[4]
    7

    # attempted using pop method, which returned the array [6, 7, 8, 9]
    array.pop(4)
    [6, 7, 8, 9]
4

2 回答 2

8

Ruby 数组索引是0基于的。

array = [1, 4, 5, 6, 7, 8, 9]
array[3] # => 6

阅读文档

数组索引从 0 开始,就像在 C 或 Java 中一样。负索引被假定为相对于数组的末尾——也就是说,索引 -1 表示数组的最后一个元素,-2 是数组中的倒数第二个元素,依此类推。

于 2013-10-21T17:44:34.880 回答
2

为了获得您需要的价值,您必须这样做:

array[3]

Ruby 从 0 开始索引,因此您需要从实际值中减去 1。

于 2013-10-21T17:47:08.883 回答