0

Given an array like this:

a = [1,2,3]

When I do a[3] it returns nil. And that makes sense because there is no more than 3 elements. However, when I do a slicing with a[3,0] or a[3,1], I get []

Why is that?

user2864740
  • 60,010
  • 15
  • 145
  • 220
blackghost
  • 683
  • 1
  • 8
  • 18
  • possible duplicate - I had asked an exactly similar question [Slicing of arrays in ruby returns different result](http://stackoverflow.com/questions/21496477/slicing-of-arrays-in-ruby-returns-different-result). Check out this [link](http://stackoverflow.com/questions/21496477/slicing-of-arrays-in-ruby-returns-different-result#comment32450100_21496503) – Anshul Goyal Sep 09 '14 at 02:48
  • It's does *not* appear to be the "same" question as that linked, in this case it's a single vs. multi-slice and the first sliced index is the same. It is `a[3]` (=> nil) vs `a[3,0]` (=> []) as opposed to `a[3,0]` (=> []) vs `a[4,0]` (=> nil). – user2864740 Sep 09 '14 at 02:53
  • @hobbs It still doesn't explain why `a[4, 0]` (not shown) evaluates to `nil`. (That's just a quirk of Ruby, really and *is* explained in the linked questions.) – user2864740 Sep 09 '14 at 02:56
  • 1
    All the cases seem to be covered in http://stackoverflow.com/questions/3568222/array-slicing-in-ruby-looking-for-explanation-for-illogical-behaviour-taken-fr (which would make a good covering-duplicate) – user2864740 Sep 09 '14 at 03:00
  • Here's an example of how `a[2,2] => [3]` and `a[3,2] = []` can be handy, when `a = [1,2,3]`. Suppose you wanted to map each element of `a` into the sum of the following two elements, except for the penultimate element, which is to map into the last element, and the last element, which is to map to zero. You could do this with an `if/elsif/else/end` construct, or a `case` statement, but it's much easier to take advantage of the way slice is defined: `(1..a.size).map { |i| a[i,2].reduce(0,:+) } => [5, 3, 0]`. Note also that `[1,2,3].insert(3,"cat") => [1, 2, 3, "cat"]`. – Cary Swoveland Sep 09 '14 at 03:37

0 Answers0