Ruby Array negative element references
Posted by anthony crumley, Mon Nov 19 22:31:00 UTC 2007
One aspect of Ruby that is non-intuitive at first is the use of negative array indexes. For instance the string ‘anthony’ would have the following indexes.
| -7 | -6 | -5 | -4 | -3 | -2 | -1 |
| a | n | t | h | o | n | y |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |
The positive numbers go from beginning to end and the negative from end to beginning. ‘anthony’[0, 1] returns ‘a’ and ‘anthony’[-1, 1] returns ‘y’. At first the negative index is a little weird but begins to make sense as it sinks in a some.
In my opinion, it would have been better if the positive numbers started with one also but I guess that is the VB programmer in me.
The real tricky part comes when you bring ranges into the mix. ‘anthony’[1..3] returns ‘nth’ and ‘anthony’[-4..-2] returns ‘hon’ which makes sense when you refer to the table above. One rule to remember is that the first number in the range must be before the second number or an empty string is returned. ‘anthony’[3..1] and ‘anthony’[-2..-4] both return ””. Now, with this in mind, what does ‘anthony’[1..-1]return? My first thought was that it would return an empty string because the number 1 is after -1. That is not true though because the positions relative to the beginning of the array are compared rather than the actual numbers. Next I thought it would return positions 1, 0, and -1 which would be ‘nay’ but that would just be weird. It actually returns ‘nthony’ because it returns everything from position 1 to position -1 reading from beginning to end. In this case 1 is the second position and -1 is the last position so everything except the letter in the first position is returned. The mixing of positive and negative indexes with ranges takes some practice so play around in IRB and you should get the hang of it.