Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a range of 2..-1 mean? (Ruby koans about_arrays.rb)

Tags:

ruby

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?

like image 433
Will Avatar asked Aug 23 '12 19:08

Will


1 Answers

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.

like image 157
KRyan Avatar answered Oct 31 '22 14:10

KRyan