当起始索引大于 (array.size -1) 时,关于 ruby Array [] 方法结果的混淆
鉴于
array = [:a,:b,:c,:d] # with 4 elements:
array[3] => :d # zero-based indices, I get that
array[4] => nil
array[5] => nil
array[3,0] => [] # OK since I asked for a slice with zero elements
Doco for array[start,length] 表示它“如果索引(或起始索引)超出范围,则返回 nil。”
array[5,0] => nil # OK
array[4,0] => [] # Hunh??
怎么会是 array[4,0]
返回一个数组而不是 nil
?
[编辑] 看起来这个已经出现了:参见 Ruby 中的数组切片:寻找不合逻辑行为的解释(取自 Rubykoans.com)
对我来说,这个解释看起来有点像挥手,但是我会接受这一点并接受 ruby 在这里违反了 PLS。
Given
array = [:a,:b,:c,:d] # with 4 elements:
array[3] => :d # zero-based indices, I get that
array[4] => nil
array[5] => nil
array[3,0] => [] # OK since I asked for a slice with zero elements
Doco for array[start,length] says that it "Returns nil if the index (or starting index) are out of range."
array[5,0] => nil # OK
array[4,0] => [] # Hunh??
How come array[4,0]
returns an array as opposed to nil
?
[edit] Looks like this has already come up: see Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)
To me the explanation looks a bit like hand waving, but I'll settle for it and just accept that ruby violates PLS here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为该文档没有正确描述该行为。但直觉上,这种行为是有道理的。就像可以在数组的开头定义一个 0 元素“条子”一样,在所有元素之前通过索引
array[0,0]
来定义,也应该可以对称地得到通过索引array[array.size,0]
,在数组末尾(所有元素之后)添加一个 0 元素“条子”。另一个例子是,直觉上应该总是可以通过在整个范围内进行索引来获取数组的副本,即 array[0,array.size] ;但如果我们在起始索引等于数组大小时返回 nil,则对于空数组来说这是不可能的。I believe that the documentation does not word the behavior correctly. But intuitively, the bahavior makes sense. Just like it is possible to define a 0-element "sliver" at the beginning of the array, before all elements by indexing
array[0,0]
, it should also be possible, symmetrically, to get a 0-element "sliver" at the end of the array, after all the elements, by indexingarray[array.size,0]
. Another example would be that it should intuitively always be possible to get a copy of an array by indexing over its whole range, i.e.array[0,array.size]
; but this would not be possible for empty arrays if we returned nil when the starting index is equal to the array size.