Please could someone explain what a range object of 2..-1 means.
Ruby koans has the following in about_arrays.rb:
def test_slicing_with_ranges
array = [:peanut, :butter, :and, :jelly]
assert_equal [:peanut, :butter, :and], array[0..2]
assert_equal [:peanut, :butter], array[0...2]
assert_equal [:and, :jelly], array[2..-1]
end
The following website (found from another answer) explains how ranges work with slicing:
Gary Wright, string/array slices
From this, I understand why the split gives the answer it does. The thing I don’t understand is WHAT range the range object is referring to. For a normal range, I can do:
(1..3).each { |x| puts(x) }
which gives the following output when executed in irb:
1
2
3
=> 1..3e
However, (2..-1).each { |x| puts(x) } gives:
=> 2..-1
So what does the range (2..-1) mean?
A negative index means “counting from the end of the array.” So
-1is the last item in the array.2..-1means from the third item to the last.