Skip to content

How to get first n characters of a string in Ruby

Feb 28, 2023Abhishek EH1 Min Read
How to get first n characters of a string in Ruby

In this article, we will see how to get the first n characters of a string in Ruby.

Consider the following string

1fruit = "watermelon"

Now you want to extract the first 5 characters from it.

You can extract the first n characters using the syntax string[0,n]. In our example:

1fruit = "watermelon"
2firstFiveChars = fruit[0,5]
3puts firstFiveChars # 👉water

The first argument is from which index to start and the second argument defines the number of characters to retrieve.

You can also use the following syntax:

1fruit = "watermelon"
2firstFiveChars = fruit[0...5] # Including 5th index
3# OR
4firstFiveChars = fruit[0..6] # Excluding 6th index

In the above code, the second argument specifies the index in the string, not the number of characters.

You can read more about it here.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com