On 2014-Nov-13, at 12:39 , George D. [email protected] wrote:
It is kind of strange.
If you look at the examples section there is a “special cases” list and your
example appears there.
I don’t know the reasons for this.
Here’s how I think about it:
[ :a, :b, :c, ]
^ ^ ^ ^ ^ ^
0 1 2 3 4
-4 -3 -2 -1
If the index “points” to positions “between” the actual elements, then
you can treat the index 3 (in this case) as still being “inside” the
Array brackets, but 4 is outside. If a slice starts “inside” the Array,
it returns an Array, but if you completely “miss” the Array, you get
nil.
example = [ :a, :b, :c, ]
(-4…4).each do |i|
puts “example[#{i}] \t#=> #{example[i].inspect}”
puts “example[#{i},2]\t#=> #{example[i,2].inspect}”
end
example[-4] #=> nil
example[-4,2] #=> nil
example[-3] #=> :a
example[-3,2] #=> [:a, :b]
example[-2] #=> :b
example[-2,2] #=> [:b, :c]
example[-1] #=> :c
example[-1,2] #=> [:c]
example[0] #=> :a
example[0,2] #=> [:a, :b]
example[1] #=> :b
example[1,2] #=> [:b, :c]
example[2] #=> :c
example[2,2] #=> [:c]
example[3] #=> nil
example[3,2] #=> []
example[4] #=> nil
example[4,2] #=> nil
Note that [2,2] can’t actually give 2 elements because the Array is
exhausted, but it returns what it can. [3,2] is similar: it runs out of
elements before it find even one, but it starts “inside” so it gives an
Array in return.
-Rob