Built-in String and Array Methods
Learn to use popular built-in Methods related to strings and arrays in Ruby.
Built-in methods for strings
Ruby provides various built-in Methods for dealing with strings. These methods are collectively called string methods.
Note: All string methods return a new string without changing the original one.
There are numerous tasks related to strings that make it easy for programmers to perform routine tasks. This section will provide examples and results of some commonly used string methods.
The methods related to case change
These methods change the letter case of the text stored in a string (say, from lowercase to uppercase). Let’s use an example program to explore case changes.
- The
capitalize()
method converts the first character of the string to uppercase. - The
downcase()
method converts all characters in the string to lowercase. - The
swapcase()
method swaps the letter case of the characters in a string—downcase becomes the uppercase and vice versa. - The
upcase()
method converts all characters in a string to uppercase.
# The methods related to case changeprint("'capitalize()' converts the first letter of string: ","educative".capitalize(),"\n")print("'downcase()' converts the string to lowercase: ","EDUCATIVE".downcase(),"\n")print("'swapcase()' swaps the cases of letters: ","eDUCATIVE".swapcase(),"\n")print("'upcase()' converts the string to uppercase: ","educative".upcase(),"\n")
The search-related methods
These methods search for the occurrence of text in a string. Let’s use an example program to explore searches.
- The
end_with?
method checks for text at the end of a string and returnstrue
orfalse
. - The
index
method searches for text in the string and returns the index of the first occurrence. - The
include?
method searches for text in the string and returnstrue
orfalse
. - The
count
method searches for characters in the string and returns the number of occurrences. - The
gsub
method searches for all occurrences of a text in the string, replaces it with different text, and returns the new string after replacement. - The
start_with?
method checks for text at the start of a string and returnstrue
orfalse
. - The
empty?
method checks if a string is empty or not.
# Search-related methods on stringsprint("'end_with?' return true if string ends with 've': ", "educative".end_with?('ve'),"\n")print("'index' returns the index of first occurrence of 'e': ", "educative".index('e'),"\n")print("'include?' returns true if 'e' is present in the string: ", "educative".include?('e'),"\n")print("'count' return the count of letter 'e' in the string: ", "educative".count('e'),"\n")print("'gsub' replace the 'e' with '..E..': ", "educative".gsub('e','..E..'),"\n")print("'start_with?' return true if string starts with 'edu': ", "educative".start_with?('edu'),"\n")print("'empty?' return true if string is empty: ", "".empty?,"\n")
Built-in methods for arrays
Ruby provides various built-in functions for dealing with arrays, usually termed array methods, which programmers use to perform routine tasks. Let’s use practice programs to learn these built-in methods related to arrays.
The value-inserting methods
The following methods are used to add values to arrays:
- The
append()
method adds an element at the end of the array. If we try to append another array, it’s added as a single element, making a nested array. - The
clone()
method creates a copy of an existing array. Future updates to the original array don’t affect the copy. This differs from the assignment operator=
, which only creates a reference to an existing array. In the case of assignment, any change to the original array is reflected in the reference. This difference is illustrated in the code below. - The
push()
method appends multiple elements to the end of the array. This method can append an array to another array, element by element. - The
insert()
method adds an element at a specified position in the array.
# The value-inserting methodsa = [1,2,3]b = [8,9]print("Array a: ",a,"\n")print("Array b: ",b,"\n")print("\nAppending 4 in array a","\n")a.append(4) # Appending 4 in array aprint("Array a: ",a,"\n")print("\nAppending complete array b as subarray in a ","\n")a.append(b) # Appending complete array b as subarray in aprint("Array a: ",a,"\n")print("Array b: ",b,"\n")print("\nCreating a new copy of array b in array c","\n")c = b.clone() # Creating a new copy of array b in array cprint("Array b: ",b,"\n")print("Array c: ",c,"\n")print("\nReferencing: array d is an other name of array b","\n")d = b # Referencing: array d is an other name of array bprint("Array d: ",d,"\n")print("\nAppends all members of b to array c","\n")c.push(b) # Appends all members of b to array cprint("Array c: ",c,"\n")print("\nInserting 15 at index 1 in array b","\n")b.insert(1,15)# Inserting 15 at index 1 in array bprint("Array b: ",b,"\n")print("Array d: ",d,"\n")
The value-removing methods
The following methods are used to remove values from arrays:
- The
clear()
method removes all the elements from the array. - The
pop()
method removes the last element from the array. - The
delete()
method removes the specified value from the array. - The
delete_at()
method removes the value from the specified index.
# The value-removing methodsd = [1,2,3,4,5,6]print("array d:",d,"\n")print("\nRemoving value from the end of array d using pop() function","\n")d.pop(1) # Removing value from the end of array d using pop() functionprint(d,"\n")print("\nRemoving the value 3 from array d using delete() function","\n")d.delete(3) # Removing the value 3 from array d using delete() functionprint(d,"\n")print("\nRemoving the value at index 1 from array d using delete_at() function","\n")d.delete_at(1) # Removing the value at index 1 from array d using delete() functionprint(d,"\n")print("\nRemoving all values array d using clear() function","\n")d.clear() # Removing all values array d using clear() functionprint(d,"\n")
The search-related methods
The following methods are used to search for values in arrays:
- The
count()
method searches for an element in the array and returns the number of occurrences. - The
index()
method searches for an element in the array and returns the index of the first occurrence.
# The search-related methodse = [1,1,3,40,4,4,4,5]print('The original array:',e,"\n")print("The number of 1s in the array:",e.count(1),"\n")print('The index of 40 in the array:',e.index(40),"\n")
The arrangement-related methods
The following methods are used to change the arrangement of values in arrays:
- The
reverse()
method reverses the order of the array. - The
sort()
method sorts the array.
# The arrangement-related methodsf = [1,1,30,40,4,4,40,5]print('The original array:',f,"\n")f = f.reverse()print('The array after reversing the elements:',f,"\n")f = f.sort()print('The array after sorting in increasing order:',f,"\n")