初学者到RUBY - 数组问题

时间:2010-04-22 09:15:19

标签: ruby

a = [ 1, 3, 5, 7, 9 ]    → [1, 3, 5, 7, 9]

a[2, 2] = ’cat’          → [1, 3, "cat", 9]

a[2, 0] = ’dog’          → [1, 3, "dog", "cat", 9]

a[1, 1] = [ 9, 8, 7 ]    → [1, 9, 8, 7, "dog", "cat", 9]

a[0..3] = []             → ["dog", "cat", 9]

a[5..6] = 99, 98         → ["dog", "cat", 9, nil, nil, 99, 98]

我能理解这个数组的最后四个修正是如何工作的,但为什么他们使用[2,2] ='猫'和[2,0] ='狗'???

这两个数字代表什么?

难道他们只能使用[2] ='狗'吗?

2 个答案:

答案 0 :(得分:4)

a[x,n]是从索引x开始的长度为n的子数组。

因此,a[2,2] = 'cat'表示“将第2和第3位的项目移除”并将其替换为'cat',这就是为什么这会取代57 - 而不仅仅是5 {1}}。

a[2,0] = 'dog'表示“在位置2之前取空子阵列并将其替换为'dog'”。这就是为什么没有元素被替换的原因(a[2] = 'dog'只会用猫替换猫)。

答案 1 :(得分:1)

如果在分配之前检查切片内容,将会很清楚

> a = [ 1, 3, 5, 7, 9 ] 
> a[2, 2]
=> [5, 7] # this mean if you assign to that, the content overwrite on that part
> a
=> [1, 3, "cat", 9]

同样适用于a [2,0] ='狗'

> a[2,0]
=> [] # it will not overwrite anything,
> a[2, 0] = "dog" #but slice starts at index 2, so it will just insert 'dog' into array
=> [1, 3, "dog", "cat", 9]

另一方面,[2]返回5,并指定将覆盖数据,因此不相同。

> a = [ 1, 3, 5, 7, 9 ]
> a[2]
=> 5
> a[2] = 'dog'
=> [1, 3, "dog", 7, 9] # a[2] got overwritten, instead of getting inserted.