4. String

4.15 Slice to get part of the string

If we want only a small part of the string then we use slice.

Let’s say that the word is “basketball”. If we want first five letters of this word then this is what we need to do.

Notice that we are starting with zero. That’s because in computer science mostly the first position is 0 and not 1. Here we are telling ruby to start from position 0 and get 6 letters.

Now let’s try to get “ball” from the string. The position of “b” is 7. However since the first position is counted as zero the position of “b” is 6th. So we will ask ruby to start from position 6 and get 4 values.

Let’s see one more example.