0
0
Rubyprogramming~5 mins

String slicing and indexing in Ruby

Choose your learning style9 modes available
Introduction
String slicing and indexing let you pick out parts or single characters from a string, like cutting a piece from a loaf of bread.
You want to get the first letter of a name to make initials.
You need to extract a word from a sentence.
You want to check or change a specific character in a password.
You want to get a substring from a longer text for display.
Syntax
Ruby
string[index]
string[start, length]
string[range]
Indexing starts at 0 for the first character.
Negative indexes count from the end (-1 is last character).
Examples
Get single characters by index. 0 is first, -1 is last.
Ruby
name = "Ruby"
puts name[0]       # R
puts name[-1]      # y
Get a slice starting at index 0 with length 5.
Ruby
text = "Hello World"
puts text[0, 5]    # Hello
Get a slice using a range from index 5 to 11.
Ruby
phrase = "Good morning"
puts phrase[5..11]  # morning
Sample Program
This program shows how to get the first and last characters and a slice of the first word from a sentence.
Ruby
sentence = "Programming is fun"
first_char = sentence[0]
last_char = sentence[-1]
word = sentence[0, 11]
puts "First character: #{first_char}"
puts "Last character: #{last_char}"
puts "First word: #{word}"
OutputSuccess
Important Notes
If you use an index outside the string length, Ruby returns nil.
Ranges include both start and end indexes.
You can use negative indexes to count from the string's end.
Summary
String indexing starts at 0 and can be negative to count from the end.
Use [index] for single characters, [start, length] or [range] for slices.
Slicing helps extract parts of strings easily.