新手问题 数组取出子元素问题

autumnwolf · 2014年11月21日 · 最后由 autumnwolf 回复于 2014年11月21日 · 1690 次阅读

为什么 3,4 时候返回时空数组,5 就返回了 nil?

   array = [:peanut, :butter, :and, :jelly]
 => [:peanut, :butter, :and, :jelly] 
2.1.2 :055 > array[3,0]
 => [] 
2.1.2 :056 > array[4,0]
 => [] 
2.1.2 :057 > array[5,0]
 => nil 
2.1.2 :058 > 

嗯,一个坑

关于Array#slice an empty array is returned when the starting index for an element range is at the end of the array. Returns nil if the index (or starting index) are out of range. 来源 ruby-doc

需要 登录 后方可回复, 如果你还没有账号请 注册新账号