Suppose we have a string str
. If str
contains only one character, for example, str = "1"
, then str[-1..1]
returns 1
.
But if the size
(length
) of str
is longer than one, like str = "anything else"
, then str[-1..1]
returns ""
(empty string).
Why does Ruby interpret string slicing like this?
Is it possible to iterate over a string in Ruby? Iterating Strings in Ruby is possible, The chars method can be used to turn a string into an array of characters. Then you can iterate over this array by using each.
string[0] is a new string that contains the first character of string . It is, in fact, syntactic sugar for string. [](0) , i.e. calling the method String#[] on the String object stored in the variable string with argument 0 .
This behaviour is just how ranges of characters work.
The range start is -1, which is the last character in the string. The range end is 1, which is the second position from the start.
So for a one character string, this is equivalent to 0..1, which is that single character.
For a two character string, this is 1..1, which is the second character.
For a three character string, this is 2..1, which is an empty string. And so on for longer strings.
To get a non-trivial substring, the start position has to represent a position earlier than the end position.
For a single-length string, index -1
is the same as index 0
, which is smaller than 1
. Thus, [-1..1]
gives a non-trivial substring.
For a string longer than a single character, index -1
is larger than index 0
. Thus, [-1..1]
cannot give a non-trivial substring, and by default, it returns an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With