Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)
I've been playing around with array slicing in ruby but I don't understand the last 2 results below:
a = [1,2,3]
a[2,1] # output is [3]
a[3,1] # output is [] ...why??
a[4,1] # output is nil ...according to the docs this makes sense
Why would a[3,1]
be an empty array while a[4,1]
is nil?
If anything, I would expect a[3,1]
to return nil as well. According to the ruby docs an array split should return nil if the start index is out of range. So why is it that a[3,1]
is not returning nil?
Note: This is on ruby 1.9.2
You're asking for the end of the array, which is []
. Look at it this way: the Array [1,2,3]
can be considered to be constructed from cons cells as such: (1, (2, (3, ()))
, or 1:2:3:[]
. The 3rd index (4th item) is then clearly []
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With