是否有某种在Ruby中看不见的阵列终止? [英] Is there some kind of unseen Array termination in Ruby?
问题描述
我写这需要阵列和COM presses可变长度并将它们转换为匹配数组长度的方法。
I am writing an method that takes variable lengths of arrays and compresses and converts them to matching array lengths.
的方法,接受从50至126的任意位置的阵列长度。 ..和调用时转换下来基于参数。这就意味着我动态访问在方法调用指定的范围。这也意味着我将访问,不会存在数组的索引。除了这一点,我访问范围可以是相等的。这是我的问题在于:它看起来与一系列访问时,数组的终止口袋行为古怪,而不是任何其他不存在的指数
The method accepts an array length of anywhere from 50 to 126 . .. and converts them down based on parameters when called. This means is I am dynamically accessing ranges that are specified at method call. This also means I will be accessing indices of the array that won't exist. In addition to this, the range I am accessing may be equal. This is where my problem lies: it appears that the terminating pocket of an array behaves strangely when accessing it with a range, as opposed to any other non-existent index
>> a = [0, 1, 2, 3, 4]
# => [0, 1, 2, 3, 4]
>> a[5]
# => nil
>> a[4..4]
# => [4]
>> a[6..6]
# => nil
>> a[5..5]
# => [] <------GGRAAAAAhhh!!! Thought you were nil
>> a[5..7]
# => [] <-------you too
>> a[6..7]
# => nil <-----but you are behaving
有谁知道为什么出现这种情况?它针对我的code空数组一个额外的测试,但我的应用程序整天在我的rails追逐这个bug下来以后更加好奇。 FWIW我在Mac OS X,补丁级别114
Does anyone know why this happens? Its an extra test against an empty array for my code, but I am more curious after chasing this bug down in my rails app all day. FWIW I am running Ruby 1.8.6 on Mac OS X, patchlevel 114
推荐答案
在超出范围的范围选择是一个特殊情况,可以作为每文档:
The out-of range range selection is a special case, and works as per the docs:
http://www.ruby-doc.org/core/类/ Array.html#M002183
虽然我会同意,它不是完全明显。
Though I'd agree that it's not exactly obvious.
这篇关于是否有某种在Ruby中看不见的阵列终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!