All posts

Ruby [0..-2] explained


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:

=> "g"

=> "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"

=> "strin"