Pop Quiz! (or, Arrays in Ruby) 0

Posted by brian Friday, November 11, 2005 19:04:00 GMT

In .NET (C# for this example), what is the result of the following?

int[] numbers = {1, 2, 3, 4, 5};<br/>
Console.WriteLine(numbers[-1]);

It’s going to throw an exception, right? Right. Specifically, an IndexOutOfRange exception.

What about in Ruby?

numbers = [1, 2, 3, 4, 5]<br/>
puts numbers[-1]

I found out (yeah, the hard way) that this returns 5. Likewise, numbers[-2] returns 4, and so on.

This is very cool, but also very important for us softies to keep in mind, since .NET pretty much makes a habit of an index of -1 to mean “not selected” when referring to a combobox, listbox, etc.

Comment


(won't be published)