I’m working my way through a Ruby tutorial (just for hoops and giggles) and while experimenting around one of the examples this behavior struck me as unexpected:
s = "hello"
s[1, 2] # => "el"
s[1 .. 2] # => "el"
s[-4 .. -3] # => "el"
s[-4, -3] # => nil ... but why?
I would have expected the last line to yield the same result as the one before it. After all it works that way with positive slice values. Where am I going wrong?
Because a negative length for the slice doesn’t make sense. The slice method takes an index, or a range of indexes, or a start and length.
Documentation for the slice method for the String class