Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby return for `str[-1..1]` what it does?

Tags:

string

ruby

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?

like image 200
YaphetS_Bo Avatar asked Nov 28 '16 01:11

YaphetS_Bo


People also ask

Can you iterate Over a string in Ruby?

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.

What does 0 mean in Ruby?

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 .


2 Answers

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.

like image 88
Peter Camilleri Avatar answered Sep 29 '22 23:09

Peter Camilleri


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.

like image 30
sawa Avatar answered Sep 29 '22 22:09

sawa