Ruby中的数组切片:不合逻辑行为的解释(摘自Rubykoans.com) [英] Array slicing in Ruby: explanation for illogical behaviour (taken from Rubykoans.com)

查看:69
本文介绍了Ruby中的数组切片:不合逻辑行为的解释(摘自Rubykoans.com)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 Ruby Koans 中的练习进行操作,并且被以下发现我无法解释的Ruby怪癖震惊:

I was going through the exercises in Ruby Koans and I was struck by the following Ruby quirk that I found really unexplainable:

array = [:peanut, :butter, :and, :jelly]

array[0]     #=> :peanut    #OK!
array[0,1]   #=> [:peanut]  #OK!
array[0,2]   #=> [:peanut, :butter]  #OK!
array[0,0]   #=> []    #OK!
array[2]     #=> :and  #OK!
array[2,2]   #=> [:and, :jelly]  #OK!
array[2,20]  #=> [:and, :jelly]  #OK!
array[4]     #=> nil  #OK!
array[4,0]   #=> []   #HUH??  Why's that?
array[4,100] #=> []   #Still HUH, but consistent with previous one
array[5]     #=> nil  #consistent with array[4] #=> nil  
array[5,0]   #=> nil  #WOW.  Now I don't understand anything anymore...

那么为什么array[5,0]不等于array[4,0]?当您从第(length + 1) 位置开始时,数组切片的行为有什么奇怪的原因吗?

So why is array[5,0] not equal to array[4,0]? Is there any reason why array slicing behaves this weird when you start at the (length+1)th position??

推荐答案

切片和索引编制是两个不同的操作,从另一个推断出一个行为就是问题所在.

Slicing and indexing are two different operations, and inferring the behaviour of one from the other is where your problem lies.

slice中的第一个参数不是元素,而是元素之间的位置,定义了跨度(而不是元素本身):

The first argument in slice identifies not the element but the places between elements, defining spans (and not elements themselves):

  :peanut   :butter   :and   :jelly
0         1         2      3        4

4仍然在数组中,几乎没有;如果请求0个元素,则得到数组的空端.但是没有索引5,所以您不能从那里切.

4 is still within the array, just barely; if you request 0 elements, you get the empty end of the array. But there is no index 5, so you can't slice from there.

当您进行索引时(例如array[4]),您指向的是元素本身,因此索引仅从0到3.

When you do index (like array[4]), you are pointing at elements themselves, so the indices only go from 0 to 3.

这篇关于Ruby中的数组切片:不合逻辑行为的解释(摘自Rubykoans.com)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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