3

Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)

I'm following Ruby Koans and I've gotten to a part that deals with an array that looks like this:

array = [:peanut, :butter, :and, :jelly]

One of the tests focuses on what array[4,0] returns, and another focuses on what array[5,0] returns.

There are only 4 elements in this array, meaning it goes up to array[3], correct? So why is array[4,0] returning a blank array while array[5,0] returns nil?

Community
  • 1
  • 1
Eric R.
  • 933
  • 1
  • 9
  • 19

3 Answers3

6

The two arguments version of the method behaves a little bit different than expected, you can get a full explanation by Gary Wright here.

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
1

array[4,0]:

len=0 and beg=4
beg > RARRAY_LEN   => false
len == 0           => return ary_new(klass, 0) => []

array[5,0]:

len=0 and beg=5
beg > RARRAY_LEN   => true => return Qnil => nil

array.c:rb_ary_subseq

VALUE
rb_ary_subseq(VALUE ary, long beg, long len)
{
     VALUE klass;

     if (beg > RARRAY_LEN(ary)) return Qnil;
     if (beg < 0 || len < 0) return Qnil;

     if (RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len) {
        len = RARRAY_LEN(ary) - beg;
     }
     klass = rb_obj_class(ary);
     if (len == 0) return ary_new(klass, 0);
scuawn
  • 106
  • 3
  • That's a lot of effort to go to in order to say "because that's the behaviour of the code that implements it". I would assume the question is really about why the implementors thought it would be a good idea to do things this way. FWIW, in Python, `None` (the equivalent of `nil`, I guess) will **never** be returned as opposed to an empty sequence. – Karl Knechtel Jul 25 '11 at 07:39
1

The [i, n] form is identifying substring boundaries and not characters

The short answer is that you are defining a substring to either return or replace.

There is a zero-length string at the beginning and at the end that needs to be identifiable.

In the two-argument index, the positions are really the individual boundaries between the characters, and there is one such boundary after the last character.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329