Integers like -1 aren’t reserved keywords, so you can’t say that they should hold a single meaning regardless of how and where they are being used. In your fruits example, -1 is being used as a return value for the sort method. In your capitalize example, -1 is being used to index a string. If you use -1 in a calculation, it will have a different use. If you use -1 to initialize a loop variable, it will have a different meaning. If you use -1 to set the loop step, it will have a different meaning. So, you must look at the situation to understand how it is being used.
As for using the return values in a sort, have a look at this post. In particular, I would encourage you to look at the stackoverflow link in that post. It gives a detailed explanation of the sort method and return values. But, yes basically a return value in a sort method of 1 means we should swap the elements, while 0 and -1 leave the elements in their existing position. After reading the stackoverflow post, if you still have questions, share your thoughts on what you find confusing.
In your capitalize example, -1 is not being used as a return value in a sort. Instead, it is being used as an index for a string. With strings and arrays, we can use 0, 1, 2 etc. to select the first, second, third element/character etc. If we want to target an element/character from the end, we can use negative indices.
For example,
name = “Frodo Baggins”
name[0] will be ‘F’
name[1] will be ‘r’
name[2] will be ‘o’
If we want to select characters from the end, then instead of counting from the start, we can use negative indices.
name[-1] will be ‘s’
name[-2] will be ‘n’
name[-3] will be ‘i’
In your example, string[0
] will target the first element of the string.
..
is used to specify a range, so string[1..-1]
says select all the characters starting from the second character of the string up to and including the last character of the string.