开发者

Beginner to RUBY - Array Question

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   开发者_JAVA百科      → ["dog", "cat", 9, nil, nil, 99, 98]

I can understand how the last four amendments to this array work, but why do they use a[2, 2] = 'cat' and a[2,0] = 'dog' ???

What do the two numbers represent?

Couldnt they just use a[2] = 'dog'?


a[x,n] is the subarray of a with length n starting at index x.

Thus a[2,2] = 'cat' means "take the items at positions 2 and 3" and replace them with 'cat', which is why this replaces 5 and 7 - not just 5.

a[2,0] = 'dog' means "take the empty subarray before position 2 and replace it with 'dog'". This is why no elements are replaced (a[2] = 'dog' would simply replace cat with dog).


It will be clear if you check slice contents before assigning it

> 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]

Also same for the a[2, 0] = ’dog’

> 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]

On the other side, a[2] returns 5, and assigned that will overwrite the data, so its not same.

> 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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜