All posts

Ruby [0..-2] explained

 ruby

When programming in Ruby you will sometimes see this code being run against an array or string [0..-1] or [0..-2], this is saying give me all the characters or the string or elements of the array that exist in this range. In ruby a negative index in a range means X from last with -1 one referencing the last item in the array or string.

This is best illustrated through a few examples. In the one below we use the negative integer to get the last item from a string and array and then we do the same thing but to get the second to last element from a string or array:

"string"[-1]
=> "g"

"string"[-2]
=> "n"

So then if we pass a range to a string or array we are saying “give me everything in this range returned as a new array or string”. So if the range is 0..-1 that means give me the first element through the last (the entire element) and if we use 0..-2 it means give me the first element up to the second to last. Below are the examples in code:

"string"[0..-1]
=> "string"

"string"[0..-2]
=> "strin"

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).