Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ruby handle array range accessing?

Tags:

arrays

range

ruby

ruby-1.8.7-p174 > [0,1][2..3]
 => [] 
ruby-1.8.7-p174 > [0,1][3..4]
 => nil

In a 0-index setting where index 2, 3, and 4 are all in fact out of bounds of the 2-item array, why would these return different values?

like image 987
Matt Humphrey Avatar asked Oct 16 '10 00:10

Matt Humphrey


People also ask

How do you access the values of an array in Ruby?

The at() method of an array in Ruby is used to access elements of an array. It accepts an integer value and returns the element. This element is the one in which the index position is the value passed in.

Is a range an array in Ruby?

Yes, the method does look like an array class. However, you need to add a pair of parenthesis to let Ruby know you are using the Array method and not the class. The resulting value is the range of values in an array format.

How does array work in Ruby?

Each element in an array is associated with and referred to by an index. Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array --- that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

What is range operator in Ruby?

Ranges as Sequences Sequences have a start point, an end point, and a way to produce successive values in the sequence. Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.


1 Answers

This is a known ugly odd corner. Take a look at the examples in rdoc for Array#slice.

This specific issue is listed as a "special case"

   a = [ "a", "b", "c", "d", "e" ]
   a[2] +  a[0] + a[1]    #=> "cab"
   a[6]                   #=> nil
   a[1, 2]                #=> [ "b", "c" ]
   a[1..3]                #=> [ "b", "c", "d" ]
   a[4..7]                #=> [ "e" ]
   a[6..10]               #=> nil
   a[-3, 3]               #=> [ "c", "d", "e" ]
   # special cases
   a[5]                   #=> nil
   a[5, 1]                #=> []
   a[5..10]               #=> []

If the start is exactly one item beyond the end of the array, then it will return [], an empty array. If the start is beyond that, nil. It's documented, though I'm not sure of the reason for it.

like image 113
Telemachus Avatar answered Oct 12 '22 02:10

Telemachus