Inside the String
Learn to access the individual elements of a string.
Collection
A collection is a general term used to group multiple values into a single unit. We use collections all the time in the real world―a book is a collection of pages, a train is a collection of train cars, and a wardrobe is a collection of clothes.
String
A string is a collection of characters, mostly treated as a single unit. It is used to store text values like a name, address, message, etc.
Initializing the string
There are various ways to initialize a string in Ruby. The following program demonstrates these methods:
String1 = 'String1 in Single Quotes \' not "'print(String1,"\n")String2 = "String2 in Double Quotes \" not '"print(String2,"\n")String3 = '''String3 in Three Single Quotes: neither \' nor "'''print(String3,"\n")String4 = '''String4 Three quotesallowmulti-line'''print(String4,"\n")
There are a few new things that we need to understand in the code above. The following are the three ways of initializing a string variable:
- Line 1: The text of
String1
is enclosed in single quotes'
'
. Here, we can add”
directly and'
preceded by\
as part of the text. - Line 4: The text of
String2
is enclosed in double quotes"
"
. Here, we can add'
directly and”
preceded by\
as part of the text. - Line 7: The text of
String3
andString4
is enclosed in three single quotes'''
'''
. Here, we can add"
directly and'
preceded by\
as part of the text. - The last method also makes it easy to assign multiple lines of text to a string variable, like in
String4
lines 10–12. This isn’t possible in the other two methods.
Accessing the characters in a string
Ruby allows us to access individual characters inside a string through an integer index number. To do this, we enclose the index number in square brackets after the string variable name, as shown in the following program:
String1 = "Educative"print(String1,"\n")print(String1[0],'=',String1[-9],"\n") # Displaying first element of stringprint(String1[1],'=',String1[-8],"\n") # Displaying second element of stringprint(String1[2],'=',String1[-7],"\n") # Displaying fourth element of stringprint(String1[3],'=',String1[-6],"\n") # Displaying fifth element of stringprint(String1[4],'=',String1[-5],"\n") # Displaying sixth element of stringprint(String1[5],'=',String1[-4],"\n") # Displaying seventh element of stringprint(String1[6],'=',String1[-3],"\n") # Displaying eighth element of stringprint(String1[7],'=',String1[-2],"\n") # Displaying ninth element of stringprint(String1[8],'=',String1[-1],"\n") # Displaying tenth element of string
The code above displays the individual characters of a string on separate lines, one by one. The first character is at the 0
index, and the index moves forward along the string in linear increments. Ruby also allows negative index numbers. The last character is at -1
index and moves backward along the string in linear decrements, as illustrated in the following figure:
Slice
A slice is a subset of characters from a string. We use the [i..f]
syntax to specify the initial and final index of the string to access a slice. There are several ways to access a slice of a string, but we have to pass both values to it.
- Use both values with
...
, as in[i...f]
, to access the slice from indexi
to indexf-1
. - Use both values with
..
, as in[i..f]
, to access the slice from indexi
to indexf
. - Use two values separated by
,
, as in[i, n]
, to access the slice ofn
characters starting from the indexi
.
The following code illustrates various ways of making slices. This code also demonstrates that it modifies an individual character within a string with the help of slices and
String1 = "Educative"print("\nCharacters between 3rd and 5th index: ")print(String1[3...5],"\n")print("\nCharacters between 3rd and 3rd-last index: ")print(String1[3...-3],"\n")String1[9]='-'print(String1,"\n")String2 = String1 + ' Learner'print(String2,"\n")String3 = String2[0...10] + '-' + String2[11..-1]print(String3,"\n")
In the code above:
- In
String1[3...5]
, we give the range...
a starting index3
and an ending index5
. The string slice contains two characters,ca
, at index3
and4
(stopping at index5
) because...
exclude the higher end of range. - In
String1[3...-3]
, we give the range...
a starting index3
and an ending index-3
. The string slice contains three characters,cat
, at index3
,4
, and5
(stopping at index-3
or6
). - Two strings can be joined or concatenated using the
+
operator, as shown inString2
. - We can directly modify an individual character at any index number like
String1[9] = '-'
. We can modify a character by using slicing and concatenation, as shown inString3
. The[0...10]
statement means that the slice is from the start of the string till the index number10-1
. The[11,-1]
statement means the slice is from index number11
to the end of the string. We can useString2
instead ofString3
on the left-hand side of the assignment.
Practice for string manipulation
The following are a few example programs to practice using strings in Ruby. Clicking the “Show Solution” button will display a program that solves the respective problem. You can copy and paste the given solution into the code widget to make sure the output of your solution matches the given solution. There may be several ways of writing correct solutions in programming.
Print the characters backward
Write a program that displays the characters of a string backwards, line by line. The length of the string is restricted to nine characters only.
Sample input
"Educative"
Sample output
e
v
i
t
a
c
u
d
E
string = "Educative"# Write your code here.
Left shift the characters in a string
Write a program that shifts the characters of a string to the left and replaces the last position with a dot.
Sample input
myString = "Educative"
Sample output
ducative.
# Write your code here.myString = "Educative"myString = myString[1...]+"."print(myString,"\n")
Reverse the string
Write a program that stores the string into another string in reverse order. The length of the string is restricted to nine characters only.
Sample input
"Educative"
Sample output
evitacudE
myString1 = "Educative"# Write your code here.
Palindrome test
A palindrome is a sequence of characters that reads the same backward and forward. Write a program that checks if a string is a palindrome. The length of the string is restricted to five characters only.
Sample input 1
"level"
Sample output 1
Palindrome
Sample input 2
"leve"
Sample output 2
Not Palindrome
string = "level"# Write your code here.