在Ruby中的数组切片:寻找解释不合逻辑的行为(从Rubykoans.com拍摄) [英] Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)

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

问题描述

我要通过红宝石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...

那么,为什么数组[5,0] 不等于数组[4,0] ?是否有任何理由为什么当你开始在(长+ 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??

推荐答案

对我来说很有意义。说的第一个号码,当你切不识别的元素,但要能定义的跨度的(而不是元素本身)元素之间的地方,依次是:

Makes sense to me. Say the first number when you slice does not identify the element, but places between elements, in order to be able to define spans (and not elements themselves):

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

因此​​,4仍然是在阵列内,勉强;如果您请求0的元素,你得到的数组的空结束。但没有指数5,所以你不能从那里分得一杯羹。

so, 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.

当你不切,但指数(如数组[4] ),你实际上是指向元素本身,所以指数只能去从0到3

When you don't slice, but index (like array[4]), you are actually pointing at elements themselves, so the indices only go from 0 to 3.

基本上我要说的是,切片和索引是两种不同的操作,并从其他推断之一的行为是你的问题所在。

Basically what I'm saying is that slicing and indexing are two different operations, and inferring the behaviour of one from the other is where your problem lies.

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

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