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

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

问题描述

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

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.

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

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