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

查看:30
本文介绍了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)th 位置开始时,数组切片的行为有什么原因吗??

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天全站免登陆