负索引如何与`Array#[]=` 一起使用? [英] How does negative index work with `Array#[]=`?

查看:42
本文介绍了负索引如何与`Array#[]=` 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着看看 Array#[]= 是如何工作的,并尝试了:

I tried to see how Array#[]= works, and played around:

enum[int] = obj → obj
enum[start, length] = obj → obj
enum[range] = obj → obj

问题 1

我有一个数组 b 在它的 0 索引处保存 nil.

I have one array b holding nil at its 0 index.

b = []
b[0]   # => nil

我尝试在下面的代码中用整数 10 替换 nil.

I tried to replace nil with integer 10 in the code below.

b[-1] = 10 # => IndexError: index -1 too small for array; minimum: 0

为什么上面的代码不起作用,而下面的代码起作用?对于大小为 1 的数组,为什么索引 0-1 的处理方式不同?

Why doesn't the code above work, but the ones below do? In case of an array with size 1, why are the indices 0 and -1 treated differently?

b[0] = 5   # => 5
b[-1] = 10 # => 10

问题 2

我创建了一个大小为 2 的数组,并执行了以下操作:

I created an array of size 2, and did the following:

a = [1,2]

a[-3] = 3       # => IndexError: index -3 too small for array; minimum: -2
a[-3] = [3]     # => IndexError: index -3 too small for array; minimum: -2
a[-3..-4] = [3] # => RangeError: -3..-4 out of range

我相信负索引永远不会增加数组的大小,但我不知道为什么.为什么下面的代码会成功?

I believe that negative index never increases the size of an array, but I don't know why. Why did the code below succeed?

a[-2..-3] = [3,4] #=> [3, 4]

推荐答案

我建议你看一下 数组文档.它出人意料地说:负索引被假定为相对于数组的末尾——也就是说,索引 -1 表示数组的最后一个元素,-2 是数组中最后一个元素的下一个元素,所以上."

I would suggest you to take a look at the first para in Array documentation. It surprisingly says: "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."

这意味着,当且仅当 |N| 时,您可以设置 a[-N]th 个元素<= a.size.这就是为什么 a = [1,2] ;a[-3] = 3 失败 (3 > 2).

That means, that you may set a[-N]th element if and only |N| <= a.size. That’s why a = [1,2] ; a[-3] = 3 fails (3 > 2).

另一方面,[可能] 没有记录 ruby​​ 数组的功能:a[INBOUNDS_IDX..NONSENSE_IDX]=SMTH插入 SMTH before INBOUNDS_IDX 索引:

On the other hand, there is [likely] not documented feature for ruby arrays: a[INBOUNDS_IDX..NONSENSE_IDX]=SMTH will insert SMTH before INBOUNDS_IDX index:

a=[1,2]
a[2..0]='a'
a[2..1]='b'
a[2..-100]='c'
# ⇒ [1, 2, "c", "b", "a"]
a[2..-1]='q'
# ⇒ [1, 2, "q"]

无意义在这里的意思是小于 INBOUNDS_IDX,不能被当作负数的索引"(这就是为什么在上面的例子中 a[2..-1]被视为 a[2..(a.size - 1)].)

Nonsense here means "less than INBOUNDS_IDX, and not treatable as index in an negative notation" (that’s why a[2..-1] in the example above is treated as a[2..(a.size - 1)].)

这篇关于负索引如何与`Array#[]=` 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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