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 -1
is the last item in the array. 2..-1
means from the third item to the last.
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